开发者

while loop loops infinitely when wrong input is entered [duplicate]

This question already has answers here: Filtering out invalid user inputs (5 answers) Closed 9 years ago.

Why does the following loop infinitely when a wrong input开发者_StackOverflow中文版 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";
    }


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).


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--

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜