C++ strcmp 无法将 'std::string {aka std::basic_string<char>}' 转换为 'const char*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23848669/
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
strcmp cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char*
提问by Jonathon Reinhart
Apologies in advance for the elementary nature of the question.
提前为问题的基本性质道歉。
I am trying to use the strcmp
function to test two strings for matching characters.
我正在尝试使用该strcmp
函数来测试两个字符串的匹配字符。
I reduced the issue to the simple code below:
我将问题简化为下面的简单代码:
#include <iostream>
#include <cstring>
using namespace std;
void compareStrings(string, string);
int main()
{
string string1 = "testString", string2 = "testString";
compareStrings(string1, string2);
return 0;
}
void compareStrings(string stringOne, string stringTwo)
{
if (strcmp(stringOne,stringTwo) == 0)
cout << "The strings match." << endl;
else
cout << "The strings don't match." << endl;
}
Could someone explain the following compiler error message?
有人可以解释以下编译器错误消息吗?
./newProgram.cpp: In function ‘void compareStrings(std::string, std::string)':
./newProgram.cpp:17:32: error: cannot convert ‘std::string {aka std::basic_string<char>}' to ‘const char*' for argument ‘1' to ‘int strcmp(const char*, const char*)'
if (strcmp(stringOne,stringTwo) == 0)
^
Thanks! Xz.
谢谢!XZ。
回答by Jonathon Reinhart
strcmp
is for C strings (null-terminated char *
). string::compare
is for C++ string
s.
strcmp
用于 C 字符串(以空字符结尾char *
)。 string::compare
用于 C++ string
s。
If you reallywant to use strcmp
with your std::string
, you can use string::c_str()
to get a pointer to the underlying C-string:
如果您真的想strcmp
与您的一起使用std::string
,您可以使用string::c_str()
来获取指向底层 C 字符串的指针:
if (strcmp(stringOne.c_str(), stringTwo.c_str()) == 0)
But of course, if you're using C++, you should actually useC++, and make use of std::string
's ==
overload.
但是,当然,如果您使用 C++,您实际上应该使用C++,并利用std::string
的==
重载。
if (stringOne == stringTwo)