cin.fail while循环输入重新输入

时间:2015-09-14 01:17:11

标签: c++ while-loop cin

试图检查输入是否是此问题的布尔变量(1或0)。

但是,每当触发while循环时(即不输入1或0),它就会失效并表示条件为真。

我希望用户能够在输入错误后重新输入输入。我该怎么做呢?

我的代码:

int main() {
bool a,b,c;
    cout << "This program will determine the value of the condition !(a||b) && c " << endl;
    cout << "Please enter boolean values for a, b, and c. (0=F, 1=T) ";

    cin >> a;
        while (cin.fail())
        {
        cin.ignore(1000,'|n');
        cin.clear();
        cout << "Error: Enter only 0 or 1" << endl;
        cout << "Enter in a new value for a" << endl;
        }
    cin >> b;
    cin >> c;
    cout << "The condition !(xx||xx)&&xx ";
    if(!(a||b) && c)
    {
        cout << "is true";
    }
    else
    {
        cout << "is false";
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您需要在while循环结束时放入cin >> a;

cin.clear()将删除错误,然后while循环将停止。

像这样:

cin >> a;
while (cin.fail())
{
    cin.clear();
    cin.ignore(1000,'\n');
    cout << "Error: Enter only 0 or 1" << endl;
    cout << "Enter in a new value for a" << endl;
    cin >> a;
}