如何在C ++中使用EOF停止后恢复输入流? [英] How to resume input stream after stopped by EOF in C++?

查看:281
本文介绍了如何在C ++中使用EOF停止后恢复输入流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,以便从终端获取两组整数输入并计算两个总和。我的目的是通过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来表示序列的结束(这是一个不寻常的接口,可能最好避免),你需要清除 ICANON 标志标准输入流(文件描述符0)的 tcgetattr() tcsetattr()。您将需要处理任何控制字符。

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.

这篇关于如何在C ++中使用EOF停止后恢复输入流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆