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

我的梦境 提交于 2019-12-11 06:39:45

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/3876107/while-loop-loops-infinitely-when-wrong-input-is-entered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!