如何在 stdin 上强制 eof ?
对于 C++ 应用程序,如何以编程方式强制 stdin 上的文件结束 (EOF)?
For a C++ application, how can I programmatically force an end of file (EOF) on stdin?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的是类 Unix 系统中的终端,请按
Ctrl-D
。在 Windows 中,Ctrl-Z
。编辑:看到“以编程方式”执行此操作的愿望后,我建议尝试
fclose(stdin)
。如果不知何故这还不够好,一个更疯狂的想法可能是使用 std::cin.rdbuf() 来将流设置为引用除真正的标准输入之外的其他内容,然后执行您想要的操作那条溪流。但这开始变得很糟糕,就像你在与计算机对抗一样,所以我想更多地了解真正的目标是什么。If you're at a terminal in a Unix-like system, hit
Ctrl-D
. In Windows,Ctrl-Z
.Edit: Having seen the desire to do this "programmatically," I suggest trying
fclose(stdin)
. If somehow that's not good enough, a crazier idea might be to usestd::cin.rdbuf()
to set the stream to refer to something other than the true stdin, and then do what you want to that stream. But this starts to smell bad, like you are fighting against the computer, so I'd like to know more about what the real goal is.事实上,你不能。只要你能从stdin读取数据,EOF就还没有达到,事实上你永远也无法达到它。不过,您可以关闭
stdin
本身。要关闭它,请执行以下操作:此后,您将无法从
stdin
读取数据。Actually, you cannot. As long as you can read data from stdin, EOF hasn't been reached, and in fact you can never reach it. You can close the
stdin
itself, however. To close it, do this:After this, you cannot read data from
stdin
.对于专门为此创建的每个流,都有一个很好的小功能可用。
它的语法类似于:
因此,在您的代码中,您可以有一个简单的条件来触发类似的内容:
这方面的文档非常稀疏,但有一些 cppreference.com 和 cplusplus.com。
There's a nice little function available for every stream created especially for this.
It's syntax is something like:
So in your code you can have a simple condition that triggers something like:
The documentation for this is pretty sparse but there's some on cppreference.com and cplusplus.com.