Converting a char to a string...
Jul 27, 2011 at 7:29pm UTC
Hello, I'm trying to compare a char[name] to a string...Ultimately I'm trying to search a text file for a specific string...so far, my code looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
int main()
{
string line, line3, line4;
char line2[3];
strcpy(line2, "aam" );
ifstream myfile ("/Users/appliedstatistics/Language/dict.txt" );
if (myfile.is_open()){
while ( myfile.good() ) {
getline (myfile, line);
if (strcmp(line, line2)==0) {
cout << line << endl;
}
}
myfile.close();
}
else cout << "Unable to open file" ;
return 0;
}
I receive the following error:
main.cpp:23: error: cannot convert `std::string' to `const char*' for argument `1' to `int strcmp(const char*, const char*)'
Is there a way to convert the string to a char, or char to string..?
Jul 27, 2011 at 7:42pm UTC
Yes to both ways. But the easiest for you would be to:
if (strcmp(myfile.c_str(), line2) == 0)
Jul 27, 2011 at 8:16pm UTC
webJose -
would your solution be use like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
int main()
{
string line, line3, line4;
char line2[3];
strcpy(line2, "aam" );
ifstream myfile ("/Users/appliedstatistics/Language/dict.txt" );
if (myfile.is_open()){
while ( myfile.good() ) {
getline (myfile, line);
if (strcmp(myfile.c_str(), line2) == 0){
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file" ;
return 0;
}
This returns an error...c_str() undeclared...Is c_str() a member of fstream? It should be the first "string" to compare right?
Jul 27, 2011 at 10:29pm UTC
Topic archived. No new replies allowed.