为什么只返回“是”? [英] 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;
}
此代码仅在控制台窗口弹出并询问是您即使在我键入no之后也可以从僵尸手中接管城市。
This code only returns Yes back, after the console window pops up and ask are you here to take over the city from zombies even after i type no it returns yes!
推荐答案
if (userInput == "yes" || "Yes")
实际上是
if ((userInput == "yes") || ("Yes"))
这是两个表达式之间的逻辑或: userInput ==是
和是
。第一个是正确的,直接评估为 bool
。第二个只是 char *
,它将隐式转换为 bool
。由于它是一个编译时间字符串,因此不能为 nullptr
,这意味着它将始终评估为 true
。反过来,这意味着整个条件始终为 true
(这就是逻辑OR的工作方式)。
正确的代码是
It's logical OR between two expressions: userInput == "yes"
and "Yes"
. The first one is correct and evaluates to bool
directly. The second one is just a char*
that will be converted to bool
implicitly. Since it's a compile time string it cannot be nullptr
, which means it will always evaluate to true
. And that, in turn, means the whole condition is always true
(that's how logical OR works).
The correct code is
if (userInput == "yes" || userInput == "Yes")
P。 S.这就是为什么我总是建议尽可能使用最高警告级别进行编译(对于MSVC, / W4
, -Wall -pedantic-errors
用于GCC和clang)。在这种情况下,大多数编译器都会生成警告。
P. S. This is why I always recommend compiling with the highest warning level possible (/W4
for MSVC, -Wall -pedantic-errors
for GCC and clang). Most compilers will generate a warning in this case.
这篇关于为什么只返回“是”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!