Jason
Jason

Reputation: 19

(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 N I 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;
}

Upvotes: 0

Views: 10660

Answers (4)

ichramm
ichramm

Reputation: 6642

((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' );

Upvotes: 0

Gio
Gio

Reputation: 3340

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') 

Upvotes: 2

cmd
cmd

Reputation: 5830

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

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

you probably ment

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

Upvotes: 1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

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.

Upvotes: 1

Related Questions