【问题标题】:Reading till new line in C++ goes in an infinite loop [duplicate]在 C++ 中读取直到换行进入无限循环 [重复]
【发布时间】:2016-09-13 23:32:35
【问题描述】:

给定以下程序

#include <iostream>
#include <string>
using namespace std;

int main() {
    int integer;
    cin >> integer;
    if (!cin) {
        string str;
        char ch;
        while ((ch = cin.get()) != '\n') {
            cout << "scanning" << endl;
            cout << "got " << static_cast<int>(ch) << endl;
        }
    }
    return 0;
}

当给定这个输入文件时(重定向输入)

x123

末尾有换行符,为什么程序会陷入死循环?在文件末尾遇到换行符后不应该停止吗?我不断将ch 的值获取为-1..

谢谢!

注意cin.ignore() 似乎无法帮助解决这里的问题

【问题讨论】:

  • 确实如此,然后当我扫描到最后尝试找到换行符时,我得到一个无限循环
  • 我手动添加了换行符。它在那里
  • 我需要cin.ignore()吗?不,没有帮助
  • 没有清除错误情况的代码,所以cin一直报错。
  • 今天我的大脑显然无法运作。对此感到抱歉。

标签: c++ c++11 cin


【解决方案1】:

如果您在std::cin(类型为std::istream)上遇到错误,则需要清除它:

int integer;
cin >> integer;
if (!cin) {
    cin.clear(); // If an error occurred, we need to clear it!
    ...

那就will work.

【讨论】:

  • 不!它只会停止无限循环,但没有任何正确!
  • 尝试 { cin >> 整数; if (cin.fail()) throw;} catch(...) { cout
【解决方案2】:

解决方案是使用cin.clear() 从失败状态中恢复,然后重试扫描直到换行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    相关资源
    最近更新 更多