Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert ‘std::string’ to ‘const char*

Tags:

c++

Hi can any one tell what wrong with this code ?.

 string s=getString(); //return string

    if(!strcmp(s,"STRING")){
         //Do something
    }

while compiling I am getting the error like

error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int strcmp(const char*, const char*)’|
like image 807
Haris Avatar asked May 29 '13 09:05

Haris


People also ask

Can I assign a string in a const char *?

You can use the c_str() method of the string class to get a const char* with the string contents.

How do I convert a string to a char in C++?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

How does stoi work in C++?

In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.

Should I use const char or STD string?

For string literals, and only for string constants that come from literals, I would use const char[] . The main advantage of std::string is that it has memory management for free, but that is not an issue with string literals.


4 Answers

strcmp accepts const char* as argument. You can use c_str method:

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

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

if(s == "STRING")
like image 101
awesoon Avatar answered Sep 23 '22 22:09

awesoon


You need to use s.c_str() to get the C string version of a std::string, along the lines of:

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

but I'm not sure why you wouldn't just use:

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

which is a lot more readable.

like image 34
paxdiablo Avatar answered Sep 24 '22 22:09

paxdiablo


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

You can also just do this:

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

Which is clearer and doesn't pretend that you're writing C.

like image 44
janm Avatar answered Sep 22 '22 22:09

janm


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

like image 39
Thibel Avatar answered Sep 24 '22 22:09

Thibel