C++ 如何使用if语句检查字符串文字是否是某个单词或短语
我对编码还是新手,一直在尝试找出简单的对话,在编译过程中我遇到了以下错误: 错误:无法将'str.std::basic_string::operator=,std::allocator>const char*good'从'std::basic_string'转换为'bool' 如果str=良好{ 及 错误:无法将'str.std::basic_string::operator=,std::allocator>const char*bad'从'std::basic_string'转换为'bool' 如果str=bad,则为else{ 我从以下代码中得到这些错误。请记住,我对这一点还是很陌生的:C++ 如何使用if语句检查字符串文字是否是某个单词或短语,c++,string,if-statement,C++,String,If Statement,我对编码还是新手,一直在尝试找出简单的对话,在编译过程中我遇到了以下错误: 错误:无法将'str.std::basic_string::operator=,std::allocator>const char*good'从'std::basic_string'转换为'bool' 如果str=良好{ 及 错误:无法将'str.std::basic_string::operator=,std::allocator>const char*bad'从'std::basic_string'转换为'bool'
// random practice on conversation
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str;
string bad;
cout << "How has your day been? \n";
cin >> str;
if (str = "good") {
cout << "Thats good to hear!\n";
}
else if (str = "bad") {
cout << "That's too bad, what happened? \n";
cin >> bad;
cout << "I'm sorry to hear that...\n";
}
else {
cout << "I'm sorry, I couldn't understand you...\n";
}
}
=不是比较运算符,而是赋值运算符。==是比较运算符
if( str == "bad" )
{
...
}
您需要双等号,否则将字符串变量str设置为good或bad,而不是检查它是否等于good或bad。在C/C++中,==运算符不适用于字符串。如果要比较两个字符串s1和s2,请使用s1.compares2或该函数的其他变体。也可以使用strncmp函数进行此操作解决了这个问题,这让我觉得自己更为原始,谢谢你的帮助。我既不能也不能相信这是唯一的问题……哦,还有很多东西要学,你的编译器真的没有给你一个关于= = vs= =?我所发布的是我得到的唯一的两个错误,我使用编译器DEV-C++。+ 5.10
if(str == "good"){
}