Why is this only returning “yes”

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 09:21:35
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.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!