当输入错误输入时,while循环无限循环

时间:2010-10-06 19:19:07

标签: c++ while-loop

为什么在输入错误输入时无限循环?我该如何纠正?

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";
    }

2 个答案:

答案 0 :(得分:3)

在输入流上遇到错误后,流将处于失败状态。您明确必须清除该流上的故障位并在之后清空它。尝试:

#include <limits> 
#include <iostream>

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

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

您可以通过检查good(),bad(),fail()或eof()的返回值来检查输入是否引发错误。这些函数只返回内部状态位的状态(即如果设置了相应位,则为true - 除了good(),显然,如果一切都按顺序,则返回true)。

答案 1 :(得分:0)

如果您有一个cin无法解析的输入,则该流将处于错误状态。

以下是如何清除错误状态,然后忽略输入的示例:

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";
    }

请注意,在尝试忽略不正确的字符之前,清除输入流的错误状态非常重要。希望有所帮助 -