condition not working, can anyone explain why that is?

后端 未结 4 387
失恋的感觉
失恋的感觉 2021-01-16 00:23

I just started learning C++ so i’m sure there is something obvious about this that i’m missing. I would love it if somebody could enlighten me. thank you!

Im trying

相关标签:
4条回答
  • 2021-01-16 00:46

    Please change your Or conditions with And condition.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        char answer{' '};
        std::cin>>answer;
    
        while (answer != 'n' && answer != 'N' && answer != 'Y' && answer != 'y') 
        {
            std::cout<<"Error: Please press 'Y' for yes and 'N' for no, followed by 'ENTER'. \n";
            std::cin>>answer;
        }
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-16 00:46

    I would had parenthesis:

    do { 
        std::cin>>answer 
    } while ((std::toupper(answer) != 'N') && (std::toupper(answer) != 'Y'));
    

    Operators have precedence and it may introduce subtle errors not to mention when using beta compiler.

    0 讨论(0)
  • 2021-01-16 00:58

    Change the || to &&. If the char is not 'n' AND the char is not 'N' AND the char is not 'Y' AND the char is not 'y' THEN display the error.

    0 讨论(0)
  • 2021-01-16 01:04

    Take the expression answer != 'n' || answer != 'N', if you think about it, since answer can't be at the same time 'N' and 'n' this will always be true, answer will allways be different from 'n' or different from 'N'. See what I mean?

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