在很长一段时间没有接触C++之后,我再次练习它。我试图编写一个 if 语句,该语句将根据给定的输入输出不同的文本。然而,我每次都收到错误的输出......
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string answer;
cout << "Hello!" << '\n';
cout << "Do you have a dog?" << endl;
cin >> answer;
if (answer == "yes" || "yeah")
{
cout << "Thats great!";
}
else if (answer == "no" || "nah")
{
cout << "Aww, thats too bad...";
}
else
{
cout << "Umm, I didn't get that." << '\n';
cout << "Could you repeat that again?" << endl;
}
return 0;
}
无论我输入什么,我都会不断收到第一个 If 语句的输出。任何输入都会显示“Thats Great!”
这是因为您使用的是条件 if (answer == "yes" || "yeah") - 编译器将其视为“answer == "yes"" OR "yeah" 并且第二个条件 ("yeah) 将始终就像在 C++ 中一样,表达式“yeah”本身就是 true,因为它是一个非空字符串文字。
使用以下语法
if (answer == "yes" || answer == "yeah")