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!
actually means
It's logical OR between two expressions:
userInput == "yes"
and"Yes"
. The first one is correct and evaluates tobool
directly. The second one is just achar*
that will be converted tobool
implicitly. Since it's a compile time string it cannot benullptr
, which means it will always evaluate totrue
. And that, in turn, means the whole condition is alwaystrue
(that's how logical OR works). The correct code isP. 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.that's not how the || operator works, if you just put "Yes" as a condition it will always evaluate to true
the reason why is because of precedence
and
get evaluated before || ( logical OR)