Cannot convert 'std :: string to' const char *

Hi, can anyone say what is wrong with this code?

string s=getString(); //return string if(!strcmp(s,"STRING")){ //Do something } 

when compiling, I get an error, for example

 error: cannot convert 'std::string' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'| 
+4
source share
5 answers

strcmp takes const char* as an argument. You can use the c_str method:

 if(!strcmp(s.c_str(),"STRING")) 

Or just use the overloaded operator== for std::string :

 if(s == "STRING") 
+17
source

You need to use s.c_str() to get a lowercase version of C std::string line by line:

 if (!strcmp (s.c_str(), "STRING")) ... 

but I'm not sure why you are not just using:

 if (s == "STRING") ... 

which is much readable.

+11
source

You can use the c_str() method on std::string , as in other answers.

You can also just do this:

 if (s == "STRING") { ... } 

Which is clearer and does not pretend to write C.

+5
source

You should use the c_str() function of std::string , which gives you a basic char array if you want to keep the C way of comparing strings.

Otherwise, you should use operator== , which can check for equality between strings and const char* .

+1
source

You must use c_str () and it should solve your problem.

+1
source

Source: https://habr.com/ru/post/1483322/


All Articles