Suppose given a non-empty text file containing a list of numbers,
1 2 3 4 5
and we read them with std::ifstream
into numerical types ( int
, double
, etc.) as well as char
int main()
{
ifstream fs {"textfile.txt"};
int val {0}; //read into ints
for (int i{0}; i < 5; ++i)
{
//read five times
fs >> val;
cout << val << " is read. Current state of file stream: "
<< bitset<3> (fs.rdstate()) << endl; //check stream state after each read
}
}
When read as numerical types, the program outputs:
1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 010
At the point when the last item of the file is read, the eofbit was set.
But the same thing doesn't happen when reading into char
s.
int main()
{
ifstream fs {"textfile.txt"};
char ch {0}; //read into chars
for (int i{0}; i < 5; ++i)
{
//read five times
fs >> ch;
cout << ch << " is read. Current state of file stream: "
<< bitset<3> (fs.rdstate()) << endl; //check stream state after each read
}
}
which outputs:
1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 000
Why is this the case?
You get EOF
when reading int
s because the stream extraction operator for int
tries to read till it finds either a whitespace or something unsuitable for an int
. So it will try to read another char
after the 5
was read, encounters the end of the file and the eofbit
gets set.
In contrast, the stream extraction operator for char
will only ever try to read one char
so it won't encounter the end of the file. Try and read 6 char
s from the file and you will also encounter EOF
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.