C++ 无法将“std::string”转换为“const char*”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16810485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:40:00  来源:igfitidea点击:

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

c++

提问by Haris

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*)'|

回答by awesoon

strcmpaccepts const char*as argument. You can use c_strmethod:

strcmp接受const char*作为参数。您可以使用c_str方法:

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

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

或者只是使用重载operator==std::string

if(s == "STRING")

回答by paxdiablo

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

您需要使用s.c_str()来获取 a 的 C 字符串版本std::string,如下所示:

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.

这更具可读性。

回答by janm

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

您可以在其他答案中使用该c_str()方法std::string

You can also just do this:

你也可以这样做:

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

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

这更清楚,不会假装你在写 C。

回答by Thibel

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

您必须使用 c_str() 并且它应该可以解决您的问题。

回答by JBL

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

如果您想保留比较字符串的 C 方式,您必须使用它的c_str()成员函数std::string为您提供底层char数组。

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

否则,您应该使用operator==可以测试字符串和const char*.