如何在CIN缓冲区中删除EOF?
我正在使用一个示例来说明我的意思:在我的Mac上,留下第一个“ while loop”,用户必须键入“ ctrl+d”。据我了解,这是通过将EOF添加到CIN缓冲区中来实现的,因此“ C> gt; X”返回false。现在,我打算在离开第一个循环后输入第二个“循环”。我如何从CIN缓冲区中清除EOF,以便“ cin>” y返回真实吗?
using namespace std;
int main()
{
int x;
int y;
while(cin >> x)
{
cout << x << endl;
}
if(cin.get()==EOF) cout << "yes" << endl;
while(cin >> y)
{
cout << y*y << endl;
}
return 0;
}
I'm using an example to show what I mean: On my Mac, to leave the first "while loop", the user has to type "CTRL+D". From what I understand, that is achieved by adding an EOF into the cin buffer, thus "c >> x" returns false. Now, I intend the user to enter the second "while loop" after leaving the first loop. How do I clear the EOF from the cin buffer, so that "cin >>" y returns true?
using namespace std;
int main()
{
int x;
int y;
while(cin >> x)
{
cout << x << endl;
}
if(cin.get()==EOF) cout << "yes" << endl;
while(cin >> y)
{
cout << y*y << endl;
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许回答很晚,但是对于其他可能有类似情况的人来说;在提示用户时,我必须处理
eof
信号,并且在程序稍后仍需要stdin
。解决此问题的一种方法是做叉/等待(一般示例),这样,可以预期的eof
的代码可以通过另一个子进程执行,然后终止而不影响父母进程的stdin
。我已经尝试过没有成功的其他解决方案之前的尝试,即
std :: cin.clear()
。如果eof
发出信号 - 通常通过 ctrl> ctrl + d (unix) )或 ctrl + z (Windows)。Maybe it's late to answer, but for others who might have a similar situation like mine; I have to handle
EOF
signal while prompting user and still needstdin
later in the program. One way to go about it is to do fork/wait (a general example), so that the piece of code whereEOF
is expected can be executed by another child process and then terminate without effectingstdin
of the parent process.I've tried before other solutions without success i.e
std::cin.clear()
. Thestdin
of your program should be shutdown, ifEOF
is signaled -- usually via CTRL+D (unix) or CTRL+Z (windows).