c++ - std::cin 来自无效输入的无限循环

标签 c++ infinite-loop cin

请阅读以下代码:

#include <iostream>
#include <cstdlib>
int main() {
    std::cout << "Please input one integer." << std::endl;
    int i;
    while (true) {
        std::cin >> i;
        if (std::cin) {
            std::cout << "i = " << i << std::endl;
            break;
        } else {
            std::cout << "Error. Please try again."<< std::endl;
            std::cin.ignore();
            std::cin.clear();
        }
    }
    std::cout << "Thank you very much." << std::endl;
    std::system("pause");
    return 0;
}

当我给 std::cin 提供无效输入时,例如 w ,然后Error. Please try again.是无限输出的。 我以为std::cin.ignore会将输入流清空,并且 std::cin.clear会将其恢复到正常状态。那么为什么会出现无限循环呢?

最佳答案

默认情况下,std::basic_istream::ignore() 仅忽略 1 个字符:

basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );

(来自 http://en.cppreference.com/w/cpp/io/basic_istream/ignore )

对于您的案例来说,更惯用的用法似乎是示例中的用法:

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

另外,请注意,您要在 ignore() 调用之前调用 clear(),因此 ignore() 的输入提取将会成功而不是立即返回。

关于c++ - std::cin 来自无效输入的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38890379/

相关文章:

c++ - getline(cin, String) 在没有另一个输入的情况下接收输入

c++ - 使用 std::cin 中的 std::setw 限制输入大小

c++ - 我不小心创建了一个病毒。这怎么是病毒?

C++变量在push_back之后没有传递它的值

java - 使用 hibernate 获取数据时无限循环

c - 我想将一个函数拆分成两个函数

c++ - Cin 没有读取我的输入

c++ - 将类转换为固定长度的 float 组

C++程序结构

javascript - Angular(ui 树)ng-repeat : infinite loop