0

I was wondering if there was anyways of stopping letters being entered for an integer. Here is the code which I have been using in my int main.

do
{
    cout << "Player 1 please enter the value of the row you would like to take ";
    cin >> row;
}while (row != 0 && row != 1 && row != 2 && row != 3);

My problem with this code is that if the user enters a letter it creates a never ending loop. Any help would be much appreciated.

lambda
  • 3,075
  • 1
  • 24
  • 31
user2078558
  • 85
  • 2
  • 9
  • Is this homework, with constraints like "only use standard C++ stuff we have already learned"? If this is something more "real-world", then there are many options, depending on OS and licensing issues. – hyde Mar 03 '13 at 11:27

2 Answers2

4

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.

jrok
  • 51,107
  • 8
  • 99
  • 136
1

Get characters one at a time and only add the number characters to the string. Use

cin.get();

in a loop.

jrok
  • 51,107
  • 8
  • 99
  • 136
QuentinUK
  • 2,687
  • 17
  • 20
  • This has the problem, that by default input is line based. This means, getchar will not return even the first char user entered, until user has entered entire line and pressed enter. – hyde Mar 03 '13 at 11:14
  • If you don't want to even see the character then you'll have to go lower for example with Windows you can use CWnd::OnKeyDown – QuentinUK Mar 03 '13 at 11:19