ifstream.peek() 到达文件末尾时的返回值
我正在 Cplusplus.com 上查看这篇文章,http://www.cplusplus。 com/reference/iostream/istream/peek/
我仍然不确定 peek() 如果到达文件末尾会返回什么。
在我的代码中,只要此语句为真(
(sourcefile.peek() != EOF)
其中源文件是我的 ifstream),程序的一部分就应该运行。
然而,它永远不会停止循环,即使它已经到达文件末尾。
EOF 不意味着“文件结束”吗?还是我用错了?
I was looking at this article on Cplusplus.com, http://www.cplusplus.com/reference/iostream/istream/peek/
I'm still not sure what peek() returns if it reaches the end of the file.
In my code, a part of the program is supposed to run as long as this statement is true
(sourcefile.peek() != EOF)
where sourcefile is my ifstream.
However, it never stops looping, even though it has reached the end of the file.
Does EOF not mean "End of File"? Or was I using it wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
查阅标准,
至于
sgetc()
,以及
下溢
,所以是的,在文件末尾返回
EOF
。一个更简单的判断方法是它返回
int_type
。由于int_type
的值只是char_type
加上 EOF,因此如果 EOF 不可能,它可能会返回char_type
。正如其他人提到的,
peek
不会提前文件位置。通常最简单也是最好的方法是在while ( input_stream )
上循环,并让无法获取额外输入的情况终止解析过程。Consulting the Standard,
As for
sgetc()
,And
underflow
,So yep, returns
EOF
on end of file.An easier way to tell is that it returns
int_type
. Since the values ofint_type
are just those ofchar_type
plus EOF, it would probably returnchar_type
if EOF weren't possible.As others mentioned,
peek
doesn't advance the file position. It's generally easiest and best to just loop onwhile ( input_stream )
and let failure to obtain additional input kill the parsing process.想到的事情(没有看到你的代码)。
EOF
的定义可能与您期望的不同,sourcefile.peek()
不会推进文件指针。您是否以某种方式手动推进它,或者您是否不断地看着同一个角色?Things that come to mind (without seeing your code).
EOF
could be defined differently than you expectsourcefile.peek()
doesn't advance the file pointer. Are you advancing it manually somehow, or are you perhaps constantly looking at the same character?EOF 适用于较旧的 C 风格函数。您应该使用
istream::traits_type::eof()
。编辑:查看评论让我确信
istream::traits_type::eof()
保证返回与EOF
相同的值,除非通过机会EOF
已在源块的上下文中重新定义。虽然建议仍然可以,但这不是所发布问题的答案。EOF is for the older C-style functions. You should use
istream::traits_type::eof()
.Edit: viewing the comments convinces me that
istream::traits_type::eof()
is guaranteed to return the same value asEOF
, unless by chanceEOF
has been redefined in the context of your source block. While the advice is still OK, this is not the answer to the question as posted.虽然这在技术上可行,但使用 ifstream::eof() 会更好
,如
(!sourcefile.eof())
While this technically works, using
ifstream::eof()
would be preferableas in
(!sourcefile.eof())