The reason is this: when you get characters from the text file using
myfile.get()
, the
ifstream
object read a new character from the file in
translated mode, i.e. it replace
CR-LF sequences from the file to a single
CR character.
Another issue is that the
ifstream::eof()
method returns true not when there are no more characters to read, but only after that you have read a new character past the end of the file.
You can fix your problem this way:
long begin, end, size;
ifstream myfile("example.txt");
begin = myfile.tellg();
myfile.seekg(0, ios::end);
end = myfile.tellg();
myfile.seekg(0, ios::beg);
size = end - begin;
ifstream::int_type character;
while ((character = myfile.get()) != EOF)
{
if (character == '\n') size -= 2;
else size -= 1;
}