Standard library doesn't provide anything that would filter characters that are entered through standard input. I believe you could use libraries like curses
to do that.
What you can do, though, is check whether input suceeded. operator>>
for int
will set the stream's state to failbit
if it couldn't extract an integer (for example, when it encountered an 'a'
or something like that. You can use extraction operators in boolean context, something like this:
cout << "Player 1 please enter the value of the row you would like to take ";
while (!(cin >> row) || (row < 0 || row > 3)) {
cout << "Invalid input, try again!\n";
// clear the error flags and discard the contents,
// so we can try again
cin.clear();
cin.ignore(std:numeric_limits<std::streamsize>::max(), '\n');
}
Note that if you enter for example 1abc
, the read will succesfuly read 1
and leave the abc
in the stream. This might not be a desired behaviour. If you wish to treat that as an error you can say
if ((cin >> std::ws).peek() != EOF) { /* there's more input waiting */ }
and act accordingly, or just unconditionaly ignore everything from the stream once you've got a value.