1

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 Answers2

1

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;
  }
raphalg
  • 448
  • 3
  • 11
0

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.

  • 1
    In my main method the variable is passed by reference so that part should be fine. Also, on the part about syntax, the "do" part of my do while loop was cut off, but it does exist – Caleb Ernst Jan 25 '21 at 01:26
  • I've updated the question so the code's a bit less confusing to read. – Caleb Ernst Jan 25 '21 at 01:30