c++ - 如何解决 cin.fail() 中的循环

标签 c++

知道为什么会这样吗?

sample run

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');

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

关于c++ - 如何解决 cin.fail() 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319827/

相关文章:

c++ - 关于c++中指针数组的问题

c++ - 我们可以对内存分配进行单元测试吗?

c++ - 写入/dev/stdout : how to send EOF? 的程序

c++ - ld 无法链接到主可执行文件

c# - 将大数据保存到文件的最快方法

c++ - 如果函数重载,Boost phoenix 成员函数运算符将无法编译

调用 delete [] 时出现 C++ HEAP 错误

c++ dll导出损坏的名称

c++ - Qt 信号和槽线程安全

c++ - 函数返回 nullptr 不返回