cin.fail while循环输入再入

cin.fail while loop input Re-Entry

只是尝试检查此问题的输入是否为布尔变量(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;
}

您需要在 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;
}