How to resume input stream after stopped by EOF in C++?(在 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 来表示序列结束(这是一个不寻常的界面,可能最好避免),您需要使用 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.
这篇关于在 C++ 中被 EOF 停止后如何恢复输入流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中被 EOF 停止后如何恢复输入流?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07