简体   繁体   中英

(C++) How to validate user input for char variables?

I'm having trouble comparing user input for a char variable. I want to check if they answered Y or N to a question. If they did not put a Y or NI want to give the user an error message and start the loop over.

Below is the test code I created as a template for the program I intend to use it for. The program loops no matter what input the user gives. Also, if the user inputs 'n' characters, they will receive 'n' "Failure!" messages along with the initial cout message each time. If they input Y it happens as well except of course it says "Success!".

I've looked around online but have yet to find anyone address this. Why does == work for equivalency checks but not != for chars (and strings as well for that matter)?

#include<iostream>

using namespace std;

int main()
{
    char answer;

    do{
        cout <<"\nPlease type Y or N." << endl;
        cin >> answer;

        if ((answer == 'Y') || (answer == 'N'))
        {
            cout << "\nSuccess!" << endl;
        }
        else
        {
            cout << "\nFailure!" << endl;
        }
    }while ((answer != 'Y') || (answer != 'N'));

    return 0;
}

The problem lays in the following line:

while ((answer != 'Y') || (answer != 'N'));

Either one of these condition is always true and you are applying logic OR, thus you can never get out of this loop. You need to change this as follows:

while (answer != 'Y' && answer != 'N') 

You misapplied Boole's logic: the negation of a disjunction is not a negation of the terms while keeping the disjunction. Instead, you need to negate the terms and use a conjunction.

answer will always be not 'Y' or not 'N'

((answer != 'Y') || (answer != 'N'))

you probably ment

((answer != 'Y') && (answer != 'N'))

((answer != 'Y') || (answer != 'N'));

Means to loop until the user enters someting different than 'Y' OR different than 'N' , so it exist when the enters 'Y' or 'N' because, of course, they are different.

You should loop as in the follwing chunk of code:

do {
  // code
} while ( answer == 'Y' && answer == 'N' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM