Allow invalid input only once

Hello. I'm trying to make a program that asks some input which has some limits (e.g. not negative), and if an invalid integer is entered, error message is printed and new try to input the integer, and if after that it's still invalid, the program exists. E.g.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int input;
cout << "Input: " << endl;
cin >> input >>;

if (input < 0)
{
cout << "Non-negative input only! Input again: " << endl;
cin >> input >>;
  if (input < 0)
  {
   cout << "Invalid input." << endl;
   return EXIT_FAILURE;
  }
}

return EXIT_SUCCESS;


That'd do it, but is there more efficient way?
Last edited on
You can do something similar with a 'while' loop, this is my idea:

1
2
3
4
5
6
int tries = 1
while(tries<2)
{
//do some stuff, increment tries when user makes an invalid input
//..
}
Last edited on
Topic archived. No new replies allowed.