Why is this only returning “yes”

前端 未结 2 1541
既然无缘
既然无缘 2021-01-28 20:05
int OnLoad() {
cout << \"Hi whats your name? \";
cin >> name;
system(\"cls\");
cout << \"Hi \" << name << \".\" << \" Are you here to         


        
相关标签:
2条回答
  • 2021-01-28 20:20

    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)

    0 讨论(0)
  • 2021-01-28 20:29
    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.

    0 讨论(0)
提交回复
热议问题