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

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

strcmp cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char*

c++strcmp

提问by Jonathon Reinhart

Apologies in advance for the elementary nature of the question.

提前为问题的基本性质道歉。

I am trying to use the strcmpfunction 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

strcmpis for C strings (null-terminated char *). string::compareis for C++ strings.

strcmp用于 C 字符串(以空字符结尾char *)。 string::compare用于 C++ strings。

If you reallywant to use strcmpwith 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)