找到 cin & 的流末尾如果流?
我正在阅读一本 C++ 教科书,作为 C++ 编程的复习。其中一个练习问题(不涉及太多细节)要求我定义一个可以将 ifstream 或 cin (例如 istream)作为参数传递的函数。从那里开始,我必须通读该流。问题是,我无法找到一种方法让这个 one 函数使用 cin 和 ifstream 来有效地找到流的末尾。也就是说,
while(input_stream.peek() != EOF)
不适用于 cin。我可以重新设计该函数来查找某个短语(例如“#End of Stream#”或其他内容),但我认为如果我传递的文件流具有这个确切的短语,那么这是一个坏主意。
我曾想过使用函数重载,但到目前为止,本书已经提到了何时需要我这样做。我可能在这个练习问题上投入了太多的精力,但我喜欢创作过程,并且很好奇是否有一种方法可以在不超载的情况下做到这一点。
I'm running myself through a C++ text book that I have as a refresher to C++ programming. One of the practice problems (without going into too much detail) wants me to define a function that can be passed ifstream or cin (e.g. istream) as an argument. From there, I have to read through the stream. Trouble is, I can't figure out a way to have this one function use cin and ifstream to effectively find the end of the stream. Namely,
while(input_stream.peek() != EOF)
isn't going to work for cin. I could rework the function to look for a certain phrase (like "#End of Stream#" or something), but I think this is a bad idea if the file stream I pass has this exact phrase.
I have thought to use function overloading, but so far the book has mentioned when it wants me to do this. I'm probably putting too much effort into this one practice problem, but I enjoy the creative process and am curious if there's such a way to do this without overloading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
eof()
对 cin 有效。你做错了什么;请发布您的代码。一个常见的障碍是,在您尝试读取流末尾后面的内容后,会设置eof
标志。这是一个演示:
及其输出:
(EOF 可以在 Windows 上使用 Ctrl-Z 生成,在许多其他操作系统上使用 Ctrl-D 生成)
eof()
does work for cin. You are doing something wrong; please post your code. One common stumbling block is thateof
flag gets set after you try to read behind the end of stream.Here is a demonstration:
and its output:
(EOF can be generated with Ctrl-Z on Windows and Ctrl-D on many other OSes)
为什么
std::cin.eof()
不起作用?当 stdin 关闭时,cin
将发出 EOF 信号,当用户使用 Ctrl+d (*nix) 或 Ctrl+z 发出信号时,就会发生这种情况( Windows),或者(在管道输入流的情况下)当管道文件结束时Why won't
std::cin.eof()
work?cin
will signal EOF when stdin closes, which will happen when the user signals it with Ctrl+d (*nix) or Ctrl+z (Windows), or (in the case of a piped input stream) when the piped file ends如果您在布尔上下文中使用流,那么它会将自身转换为一个值,如果尚未到达 EOF,则该值等于 true;如果尝试读取超过 EOF,则该值等于 false(不是,如果存在,则该值也为 false)是之前从流中读取的错误)。
由于流上的大多数 IO 操作都会返回流(因此它们可以链接起来)。您可以执行读取操作并在测试中使用结果(如上所述)。
因此,有一个从流中读取数字流的程序:
If you use a stream in a boolean context then it will convert itself into a value that is equivalent to true if it has not reached the EOF and false if an attempt has been made to read past the EOF (not it is also false if there was a previous error reading from the stream).
Since most IO operations on streams return the stream (so they can be chained). You can do your read operation and use the result in the test (as above).
So a program to read a stream of numbers from a stream: