While loop, C++ question. Please help

Hi, first post here, I hope i’m posting this question in the right place.
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 to create a loop in c++ that checks the char value of a variable ( it can be any one of these “Y” ,“y”, “N”, “n”), returns an error message if the wrong character is pressed and asks user for new input. If the input is correct, it should continue.

for some reason even though i type in the correct input, the error message gets printed. I tried this with an if/else statement and it still ignores the conditions and types out the error msg even though the input is correct.


char answer{' '};        // Initialize char with nothing.
std::cin>>answer;     // take user input 
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;
}

nevermind i got it.

it needs to be && not ||
logic…



char answer{' '};        // Initialize char with nothing.
std::cin>>answer;     // take user input 
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;

}

Right because you want to loop while it’s incorrect so having any of those characters are entered then need that entire expression needs to be false.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms