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 停止后如何恢复输入流?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01