views:

117

answers:

2

Why does the following loop infinitely when a wrong input is entered? How do I correct this?

int operation;
    while (true) {
        cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. ";
        cin >> operation;
        if (operation >= 1 && operation <= 5) break;
        cout << "Please enter a number from 1 to 5, inclusive.\n";
    }
+1  A: 

If you have an input that cin cannot parse, the stream will be in an error state.

Here is an example of how you can clear the error state, and then ignore the input:

int operation;
while (true) {
cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. ";
        cin >> operation;
        if (cin.fail())
        {
            cout << "Not a number " << endl;
            cout << "Please enter a number from 1 to 5, inclusive.\n";
            cin.clear();
            cin.ignore(100, '\n');
            cin >> operation;
        }
        if (operation >= 1 && operation <= 5) break;
        cout << "Please enter a number from 1 to 5, inclusive.\n";
    }

Note that it is important to clear the error state of the input stream before trying to ignore the incorrect characters. Hope that helps--

davecoulter
+3  A: 

After an error is encountered on the input stream, the stream will be in a failure state. You explicitly have to clear the failure bits on that stream and empty it afterwards. Try:

#include <limits> 
#include <iostream>

...
...
// erroneous input occurs here

std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

You can check if the input raised an error by checking the return value of good(), bad(), fail() or eof(). These functions just return the state of the internal status bits (i.e. true if the according bit is set - except for good(), obviously, which will return true if everything is in order).

Jim Brissom
this works but when I enter a correct input I must press enter twice to receive the next prompt. How do I avoid this so I only need to enter once?
idealistikz
I already answered that: Check if an error occurred and *only then* clear the stream.
Jim Brissom