c++ - 使用 C++ IO istream 对象读取导致无限循环

标签 c++ io

如果输入字符串作为输入,则以下函数会导致无限循环。

istream & inputFunc(istream &is)
{
   int ival;
    // read cin and test only for EOF; loop is executed even if there are other IO failures
    while (cin >> ival, !cin.eof()) {
        if (cin.bad())         // input stream is corrupted; bail out
            throw runtime_error("IO stream corrupted");
        if (cin.fail()) {                        // bad input
            cerr<< "bad data, try again";        // warn the user
            cin.clear(istream::failbit);         // reset the stream
            continue;                            // get next input
        }
        // ok to process ival
        cout << "you entered: " << ival << endl;
    }



}

如果输入字符串作为输入,则以下函数会导致无限循环。

输出:

再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据,再试一次坏数据, try again bad data, try again bad data, try again bad data, try again bad data, try again bad data, try again bad data, try again bad data, try again bad data, try again bad data,

最佳答案

你需要做两件事:

1) 清除状态如下:cin.clear(istream::goodbit);

2) 清除状态后一次跳过一个字符,因为你不知道下一个数字从哪里开始:

 char c;
 cin >> c;

关于c++ - 使用 C++ IO istream 对象读取导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1957495/

相关文章:

c++ - 如何以日期时间格式获取 Win32_OperatingSystem.LastBootUpTime

c++ - std::regex 未定义行为

c++ - 调用构造函数而不创建对象

c++ - 用于谷歌云消息传递的 QNetworkAccessManager

python - 如何将 'print' 输出重定向到文件?

c - #including 标准库是如何工作的?

c++ - OOP 中的正确方法。游戏示例。 Player::walk 还是 Map::playerWalk?

c++ - 缓冲输入与标准输入

c++ - 库 'stdio' 与 'iostream' 的速度和稳定性

java - 使用 Eclipse 处理 Java 时出现 FileNotFoundException