如何在cin.fail()中求解循环

How to solve the loop in cin.fail()

本文关键字:循环 cin fail      更新时间:2023-10-16

知道为什么会发生这种情况?

样本运行

void askNQ(int &noq)
{
    bool x = true;
    while (x)
    {
        int i;
        cout << "How many questions would you like(out of " << noq << ")?" << endl;
        cin >> i;
        if (cin.fail())
        {
        cin.clear();
        cin.ignore();
        cout << "Sorry, that is not valid." << endl;
        x = true;
        }
        else if (i > noq)
        {
            cout << "Sorry, that is too many." << endl;
            x = true;
        }
        else if (i <= 0)
        {
            cout << "Sorry, that is too less." << endl;
            x= true;
        }
    }
}

cin.ignore();实际上是呼叫cin.ignore(1, char_traits<char>::eof());

因此,您不会从任何剩余的新线中清理缓冲区。

以下内容应解决您的问题:

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

它清除了下一个新线字符,无论它在缓冲区中有多远(出于所有实际目的)。

您应该在命令行中输入数字,因为变量" i"是整数。