我在使用 C++ 中的 if 语句和字符串/字符时遇到了一些麻烦。这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "-----------------------------" << endl;
cout << "|Welcome to Castle Clashers!|" << endl;
cout << "-----------------------------" << endl;
cout << "Would you like to start?" << endl;
string input;
cout << "A. Yes ";
cout << "B. No " << endl;
cin >> input;
if(input == "a" || "A"){
cout << "Yes" << endl;
}else{
if(input == 'b' || 'B'){
return 0;
}
}
return 0;
}
在我的 if 语句中,它检查字符串输入是否等于 yes,如果不是,它应该转到 else 语句。这就是问题开始的地方,一旦我在控制台中运行我的程序,当我输入除“a”或“A”之外的任何内容时,它仍然说是。我试过用字符/字符来做,但我得到了相同的输出。谁能帮助我?
最佳答案
应该是 input == "a"||输入 == "A"
。您必须单独测试每个案例。现在你的代码相当于 (input == "a") || “A”
,其计算结果为 true
,因为 “A”
会衰减为非零指针。
关于c++ - 谁能帮我解决 C++ 中的 if 语句和字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705839/