【问题标题】:cin won't stop after file input文件输入后cin不会停止
【发布时间】:2019-03-22 03:33:20
【问题描述】:

在直接从命令行输入文件后,我正在尝试使用 cin 来读取 int。这是我的文件:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

它们是 81 个数字。这是有问题的代码:

#include <iostream>
using namespace std;

int main()
{
    int array[81];
    for(int i = 0; i < 81; i++)
        cin >> array[i];

    int x = 999;
    cin >> x;
    cout << x << endl;

    return 0;
}

我尝试这样输入文件: ./a.out &lt; myfile

但是,cin &gt;&gt; 不会停止并直接打印 999 作为输出。我试过cin.clear()cin.ignore(INT_MAX, 'n') 但它们都不起作用。然后我想输入这样的文件有什么特别之处,所以我在运行 a.out 后输入所有 81 个数字(不使用&lt; myfile 输入),如果我这样做,程序将继续输入并且永远不会停止或打印。

我不知道我遇到了什么......?

【问题讨论】:

  • ignore 的形式是std::cin.ignore (std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');,包括&lt;limits&gt;

标签: c++ cin


【解决方案1】:
cin >> x;

失败,您的代码无法检测到它。使用:

if ( cin >> x )
{
   // Reading to x was successful. Use it.
   cout << x << endl;
}
else
{
   // Reading to x was not successful. Figure out what to do.
}

作为一般原则,检查每个 IO 调用的状态。准备好在每次这样的电话后处理失败。在您验证调用成功之前,不要使用您希望从 IO 操作中获得的任何数据。从长远来看,这将为您省去很多心痛。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多