Why, if you use fptr.eof () and read by a symbol, it reads the last symbol (-1 'I ’), although it isn’t there! How to deal with it?
2 answers
Alternatively, you can use the istream.peek() < 0 construct to test for EOF.
- Alexey's option suited me perfectly. Thank. I will keep in mind for the future. - Ray
When working with fstream in C++ you cannot use fstream::eof() as a condition for exiting the loop. This is the implementation detail, you can read in more detail, for example, here
In short, eof() function returns "true" after the program attempts to read past the end of the file , that is, the eof() flag eof() set only after an attempt has been made to read outside the file.
In this case, returning -1 in your case is just an attempt to read "outside the file" , after which the corresponding fact is established ( -1 corresponds to the EOF code in the implementation of the streams).
Generally speaking, this is not the most obvious part of the streams, but there is a fairly good explanation of why this is implemented in this way. If interested, I can clarify.
A good way to read a C++ style file is to istream_iterator'ов as an example:
#include <string> #include <fstream> #include <streambuf> std::ifstream stream("input.file"); std::string s((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>()); If it is known that the file is large and you don’t want to completely trust the memory allocation mechanism that runs inside std::string , the solution may look like this:
std::ifstream stream("input.file"); std::string s; stream.seekg(0, std::ios::end); s.reserve(stream.tellg()); stream.seekg(0, std::ios::beg); s.assign((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());