如何在CIN缓冲区中删除EOF?

发布于 2025-01-22 06:02:39 字数 497 浏览 4 评论 0原文

我正在使用一个示例来说明我的意思:在我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乄_柒ぐ汐 2025-01-29 06:02:39

也许回答很晚,但是对于其他可能有类似情况的人来说;在提示用户时,我必须处理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 need stdin later in the program. One way to go about it is to do fork/wait (a general example), so that the piece of code where EOF is expected can be executed by another child process and then terminate without effecting stdin of the parent process.

I've tried before other solutions without success i.e std::cin.clear(). The stdin of your program should be shutdown, if EOF is signaled -- usually via CTRL+D (unix) or CTRL+Z (windows).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文