Converting a char to a string...

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..?
Yes to both ways. But the easiest for you would be to:

if (strcmp(myfile.c_str(), line2) == 0)
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?
The method c_str() is part of std::string, which I assume is what you are using here. http://www.cplusplus.com/reference/string/string/c_str/
Topic archived. No new replies allowed.