Why is this only returning “yes”

2019-03-05 04:35发布

问题:

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;
}

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!

回答1:

if (userInput == "yes" || "Yes")

actually means

if ((userInput == "yes") || ("Yes"))

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. 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.



回答2:

that's not how the || operator works, if you just put "Yes" as a condition it will always evaluate to true

if (userInput == "yes" || userInput == "Yes") {
    cout << "Yes" << endl;
}

the reason why is because of precedence

userInput == "yes"

and

userInput == "Yes"

get evaluated before || ( logical OR)