cin.当循环输入时失败

cin.fail while loop input Re-Entry

本文关键字:失败 输入 循环 cin      更新时间:2023-10-16

只是试图检查输入是否是布尔变量(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;
}

你需要把cin >> a;放在while循环的末尾。

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