Validating Integer Input

How can I validate that an input is an integer and is within certain numbers?

I tried this which did not work:
1
2
3
4
5
6
7
8
9
10
11
bool valid = false;
int choice = 0;
while(!valid) {
  cout << "Enter something\n";
  if(!(cin >> choice)) {
    cout <<"Invalid input. Try again.\n";
  }
  else {
    valid = true;
  }
}


For some reason, if I enter something like 's', it will choose to repeat the error message without letting me enter a new input.
New to this myself but this might work.
1
2
3
4
5
6
7
8
//    char a = getch();
//    bool found = false;
//    while (a < '1' || a > '6') //only accepts 1-5 input from keyboard for switch
//    {
//        a = getch();
//    }
    
//      cout << "You chose " << a << endl; 


Leppie. (Maybe I shouldn't post yet)!
Hope it helps!
Simple stuff: http://www.cplusplus.com/forum/beginner/18258/#msg92955
Less simple stuff: http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827

The simple way works for homework and the like. It will accept inputs of the form "123x" though, reading the integer '123' and leaving the 'x' behind. This may or may not be useful, depending on whether or not your input should have spaces between things.

The less simple way is to make sure the input does not validate when something like "123x" is entered. However, the way it is done in the link I gave you requires the user to have only one thing on a line. (That is, the answer has to be "123" + ENTER.) The simpler way would allow you to have more than one thing on a line...

Perhaps I'll write up an article with both these ways plus an advanced, no ENTER necessary input validation method... (so that the >> operators can be used instead of requiring the user to input only one item per line).
Topic archived. No new replies allowed.