C++: Infinite loops from input validation

Viewed 110

So I have this method where I have to intake a single value (an integer with a value greater than 1), and loop back to the user initialization if the value given is seen to be outside of those above parameters.

The issue I'm having is when a letter is input to the console the program either interprets the letter as 0 (which is a special number used for exiting the program), or (when I attempt to give a dummy value) will enter an infinite loop where (I believe) the program just keeps inputting the dummy value rather than receiving a new input from the user.

void input(int &n)
{
   do
   {  //prompt
      cout << "Input an integer number greater than 1:" << endl;

      //initialization and check for non-int value
      if (!(cin >> n))
      {
         cout << "THE NUMBER INPUT IS NOT RECOGNISED AS AN INTEGER, TRY AGAIN." << endl;
         n = 1;
      }

      //checks for special int values
      if (n == 0)
         exit(0);
      else if (n < 1)
         cout << "INPUT VALUE OF " << n << " IS NOT ALLOWED, TRY AGAIN." << endl;

   } while (n <= 1);
}

Above is what the program looks like with the dummy value implanted. Any suggestions are welcome, thanks in advance.

2 Answers

What's happening in your code is that whenever you input a letter, cin keeps its invalid state for subsequent inputs, so you have to clear it and remove bad inputs first. So you can do something like this :

if (!(cin >> n)) {
    cout << "THE NUMBER INPUT IS NOT RECOGNISED AS AN INTEGER, TRY AGAIN." << endl;
    cin.clear();
    while(cin.get() != '\n');
    n = 1;
  }

Have you declared the variable? I mean the given code will show error as you have not declared that 'n' is an integer. also, I think the syntax you're using is wrong. either you can do

while(condition)
{
    statement(s)
}

or you can do

do{
    statement(s)
}
while( condition );

The above given code should show error as per my knowledge.

Related