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*)’|
You can use the c_str() method of the string class to get a const char* with the string contents.
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.
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.
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.
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")
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.
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.
You must use c_str() and it should solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With