为什么这只返回 "yes"
Why is this only returning "yes"
int OnLoad() {
cout << "Hi whats your name? ";
cin >> name;
system("cls");
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl;
cin >> userInput;
if (userInput == "yes" || "Yes") {
cout << "Yes" << endl;
}
else if (userInput == "no" || "No") {
cout << "No" << endl;
}
else {
cout << "I don't understand." << endl;
}
return 0;
}
int main() {
OnLoad();
system("pause");
return 0;
}
仅此代码 returns 是的,在控制台弹出后 window 询问你是来这里从僵尸手中接管城市即使我输入否 returns 是的!
if (userInput == "yes" || "Yes")
实际上意味着
if ((userInput == "yes") || ("Yes"))
两个表达式之间的逻辑或:userInput == "yes"
和 "Yes"
。第一个是正确的,直接计算为 bool
。第二个只是一个 char*
,它将被隐式转换为 bool
。因为它是编译时字符串,所以它不能是 nullptr
,这意味着它将始终计算为 true
。反过来,这意味着整个条件总是 true
(这就是逻辑或的工作原理)。
正确的代码是
if (userInput == "yes" || userInput == "Yes")
P。 S. 这就是为什么我总是建议使用尽可能高的警告级别进行编译(/W4
for MSVC,-Wall -pedantic-errors
for GCC and clang)。大多数编译器会在这种情况下生成警告。
不是这样的 ||运算符有效,如果您只是将 "Yes" 作为条件,它将始终评估为 true
if (userInput == "yes" || userInput == "Yes") {
cout << "Yes" << endl;
}
原因是因为优先级
userInput == "yes"
和
userInput == "Yes"
在||之前得到评估(逻辑或)
int OnLoad() {
cout << "Hi whats your name? ";
cin >> name;
system("cls");
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl;
cin >> userInput;
if (userInput == "yes" || "Yes") {
cout << "Yes" << endl;
}
else if (userInput == "no" || "No") {
cout << "No" << endl;
}
else {
cout << "I don't understand." << endl;
}
return 0;
}
int main() {
OnLoad();
system("pause");
return 0;
}
仅此代码 returns 是的,在控制台弹出后 window 询问你是来这里从僵尸手中接管城市即使我输入否 returns 是的!
if (userInput == "yes" || "Yes")
实际上意味着
if ((userInput == "yes") || ("Yes"))
两个表达式之间的逻辑或:userInput == "yes"
和 "Yes"
。第一个是正确的,直接计算为 bool
。第二个只是一个 char*
,它将被隐式转换为 bool
。因为它是编译时字符串,所以它不能是 nullptr
,这意味着它将始终计算为 true
。反过来,这意味着整个条件总是 true
(这就是逻辑或的工作原理)。
正确的代码是
if (userInput == "yes" || userInput == "Yes")
P。 S. 这就是为什么我总是建议使用尽可能高的警告级别进行编译(/W4
for MSVC,-Wall -pedantic-errors
for GCC and clang)。大多数编译器会在这种情况下生成警告。
不是这样的 ||运算符有效,如果您只是将 "Yes" 作为条件,它将始终评估为 true
if (userInput == "yes" || userInput == "Yes") {
cout << "Yes" << endl;
}
原因是因为优先级
userInput == "yes"
和
userInput == "Yes"
在||之前得到评估(逻辑或)