'Return value of ifstream.peek() when it reaches the end of the file
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?
Solution 1:[1]
Things that come to mind (without seeing your code).
EOFcould 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?
Solution 2:[2]
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.
Solution 3:[3]
#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;
}
Solution 4:[4]
While this technically works, using ifstream::eof() would be preferable
as in
(!sourcefile.eof())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.E.D. |
| Solution 2 | |
| Solution 3 | Taryn |
| Solution 4 | L I W |
