Return value of ifstream.peek() when it reaches the end of the file

余生颓废 提交于 2019-12-10 18:41:40

问题


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?


回答1:


Consulting the Standard,

Returns:traits::eof() ifgood()isfalse. Otherwise,returnsrdbuf()->sgetc().

As for sgetc(),

Returns: If the input sequence read position is not available, returns underflow().

And underflow,

If the pending sequence is null then the function returns traits::eof() to indicate failure.

So yep, returns EOF on end of file.

An easier way to tell is that it returns int_type. Since the values of int_type are just those of char_type plus EOF, it would probably return char_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 on while ( input_stream ) and let failure to obtain additional input kill the parsing process.




回答2:


Things that come to mind (without seeing your code).

  • EOF could be defined differently than you expect
  • sourcefile.peek() doesn't advance the file pointer. Are you advancing it manually somehow, or are you perhaps constantly looking at the same character?



回答3:


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 as EOF, unless by chance EOF 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.




回答4:


#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//myifstream_peek1.cpp
int main()
{
 char ch1, ch2;
 ifstream readtext2;
 readtext2.open("mypeek.txt");
 while(readtext2.good())
 {
 if(readtext2.good())
 {
  ch2 = readtext2.get();   cout<< ch2;
 }
 }
   readtext2.close();
 //
 ifstream readtext1;
 readtext1.open("mypeek.txt");
 while(readtext1.good())
    {
    if(readtext1.good())
     {

        ch2 = readtext1.get();
        if(ch2 ==';')
            {
             ch1= readtext1.peek();
             cout<<ch1;  exit(1);
            }
            else {  cout<<ch2; }
        }

    }
    cout<<"\n end of ifstream peeking";
   readtext1.close();
return 0;
}


来源:https://stackoverflow.com/questions/3712379/return-value-of-ifstream-peek-when-it-reaches-the-end-of-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!