当其中一个字符串来自cin时,无法比较两个字符串.这里怎么了

Unable to compare two strings when one of them is from cin. What is wrong here?

本文关键字:字符串 比较 怎么了 这里 两个 一个 cin      更新时间:2023-10-16
void Display::getInput(){
cout << endl << endl << "Enter Command: ";
char input[MAX_LENGTH];
cin >> input;
if (input == "start"){
startMenu();
}

我得到了这个错误,但我不确定为什么,因为我总是可以使用这个语法进行比较。。

Display.cpp:在成员函数"void Display::getInput()"中:

Display.cpp:20:16:warning:与中的字符串文字结果进行比较如果(input="start"){

要比较C样式字符串,需要使用strcmp。否则,将input更改为字符串(std::string),而不是字符数组。您正在比较两个指针,其中一个指向文字,另一个指向数组,因此它们永远不可能相等。

您不能像那样比较C风格的字符串,而是使用strcmp进行比较,成功时返回0,失败时返回非零。

或者您可以使用类string:

int main(){
char szInput[100];
std::cin.getline(szInput, 100);
const char* szTest = "Hello";
if(!strcmp(szInput, szTest))
std::cout << "Identical" << std::endl;
else
std::cout << "Not identical" << std::endl;

std::string sInput;
std::getline(std::cin, sInput); // getline for white-spaces
std::string sTest = "Welcome there!";
if(sTest == sInput)
std::cout << "Identical" << std::endl;
else
std::cout << "Not identical" << std::endl;
return 0;
}
  • 我使用getline而不是cin来计算空白字符数