在 C++ 中被 EOF 停止后如何恢复输入流?

2022-01-04 00:00:00 io c++

我想编写一个程序,以便从终端获取两组整数输入并计算两个总和.我的意图是通过EOF(按Ctrl + D)将两组输入分开.这是我的代码:

I want to write a program so that it takes two sets of integer input from terminal and computes two sums. My intention is to separate the two sets of input by EOF (pressing Ctrl+D). Here is my code:

#include <iostream>
using namespace std;

int main(){
    int i,sum=0;
    while((cin>>i).good())
        sum+=i;
    cout<<"Sum 1 is "<<sum<<endl;
    cin.clear();
    sum=0;
    while((cin>>i).good())
        sum+=i;
    cout<<"Sum 2 is "<<sum<<endl;
    return EXIT_SUCCESS;
}

编译后的程序对于第一组整数输入运行良好.但是当我按下 Ctrl+D 时,第一个总和被计算并打印出来,并且没有采取任何进一步的输入,将第二个总和打印为 0.所以基本上第二个 while 循环在一开始就失败了,即使 cin.iostate 有在它之前被设置好.那么为什么会发生这种情况呢?我应该如何更改程序以便第二个 while 循环按预期进行?

The compiled program worked fine for the first set of integer inputs. But as soon as I pressed Ctrl+D, the first sum was computed and printed and, without taking any further input, printed the second sum as 0. So basically the second while loop failed at the very beginning, even though cin.iostate had been set to good before it. So why did this happen? How should I change the program so that the second while loop would proceed as intended?

推荐答案

当您在 tty 处于规范模式时使用 Ctrl-D 时,它会关闭系统级管道.无论您对 std::cin 做什么,都不会将流恢复到良好状态.如果您坚持使用 Ctrl-D 来表示序列结束(这是一个不寻常的界面,可能最好避免),您需要使用 tcgetattr() 清除 ICANON 标志tcsetattr() 用于标准输入流(文件描述符 0).您将需要处理任何控制字符.

When you use Ctrl-D while the tty is in canonical mode it closed the system level pipe. Whatever you do to std::cin won't restore the stream into a good state. If you insist in using Ctrl-D to signal the end of the sequence (which is an unusual interface and probably best avoided), you'll need to clear the ICANON flag using tcgetattr() and tcsetattr() for the standard input stream (file descriptor 0). You will need to deal with any control characters.

阅读第一次失败可能更容易,clear() 状态和 ignore() 有问题的字符或检查它们是否有一个特定的值.

It is probably easier to read up to the first failure, clear() the state and either ignore() the offending character(s) or check that they have a specific value.

相关文章