Sadij Sadij - 2 months ago 6x
C++ Question

How to do input validation simply in C++?

I want to give an error message if the input is neither character

but I can't get it to work! I looked up some other answers but they mostly use
method which I didn't understand at all. I just started programming and error handling is in Chapter 20 or 21. Help me out with the most simple way as possible.

This is what I've tried:

cout << "Enter 'c'(even) or 'h'(odd): ";
cin >> your_guess;

if((your_guess != ('c' || 'h')) == false) {
cout << "Wrong Input. Game is restarting... " << endl;
// restart the game ...

But it always says
Wrong Input. ...

(your_guess != ('c' || 'h')) == false

is wrong. ('c' || 'h') simply evaluates to true. The built-in operator|| takes two bool arguments:

bool operator||(bool, bool)

And since 'c' and 'h' are both not NUL characters, they convert to true.
true OR true is true. The language doesn't create some magical entity with which you can do operator==/operator!= with char to see if the character is among those you've listed.

Then, later the bool and char are promoted to int to do the inequality check. I'd guess your_guess won't be equal to 1. And I don't mean '1' (ASCII 49), but 1 (ASCII 1). So you've effectively written if(true)...

What you meant to say is:

(your_guess != 'c' || your_guess != 'h') == false


!(your_guess != 'c' || your_guess != 'h')


your_guess == 'c' && your_guess == 'h' // your_guess equal 'c' and 'h' at once?

and now you see that there's something wrong with the logic.

The right code for the condition is one of these:

your_guess != 'c' && your_guess != 'h'
!(your_guess == 'c' || your_guess == 'h')

It's just De Morgan's laws all around.

How to do input validation simply in C++?

If the above is not simple for you, you can use switch (because you're probably going to use it anyway). But each case tests variable against compile-time constant.

If the letters you want to check for are stored in a variable, I suggest this:

std::string valid_characters = "ch"; // this will be our "magical entity"

if(valid_characters.find(your_guess) == std::string::npos)
    // you have entered a character that is not 'c' nor 'h'