13

What is 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*)’|

8
  • 2
    You want if ( s == "STRING" ). strcmp is the const char* version. (You could use if (!strcmp(s.c_str(), "STRING"), but don't). Commented May 29, 2013 at 9:42
  • 1
    Did you look at the documentation for strcmp to see what arguments it accepts? Why do you even use strcmp like that when you already have an std::string that defines operator==? Commented May 29, 2013 at 9:42
  • 5
    @BoBTFish (s == "STRING") in this case. Commented May 29, 2013 at 9:43
  • 5
    @Rakkun: that's not good practice... the std::string type overloads comparison to a const char* to avoid creating a std::string temporary as your suggested code does.... Commented May 29, 2013 at 9:48
  • 4
    The beauty of C++: Where string == "foo" means exactly what it says. Commented May 29, 2013 at 9:51

5 Answers 5

32

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")
Sign up to request clarification or add additional context in comments.

4 Comments

I am going to use if (s == "STRING") , but instead of this can I use if(getString() =="STRING")
My code is just like this pastebin.com/raw.php?i=rDcPApix And if do like this if (s == "STRING") I am getting the result.
Your code works for me. Example
Hi thanks for your response. That was my coding problem, any way I solved it.
12

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.

Comments

5

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.

Comments

3

You must use the c_str() member function of std::string that gives you the underlying char array, if you want to keep the C way of comparing strings.

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

Comments

1

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

1 Comment

That is one way, but it is the worse way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.