While derpface's answer is definitely correct, it often returns unexpected results. The reason for this is because, at least on my operating system (Mac OSX 10.9.5), many text editors terminate their files with an end-line character.
For example, when I open vim, type only one βaβ character (no return) and save, now the file will contain (in hexadecimal format):
61 0A
Where 61 is the letter "a" and 0A is the end of line character.
This means that the derpface code will return an empty string for all files created by such a text editor.
Although I can, of course, imagine cases where a file ending with an "end line" should return an empty line, I think that ignoring the last character of the "end line" would be more appropriate when working with regular text files; if the file ends with the "end line" symbol, we will properly ignore it, and if the file does not end with the "end line" symbol, we do not need to check it.
My code to ignore the last character of the input file:
#include <iostream>
It will display:
final line length: 1 final line character codes: 61 final line: a
In the single file 'a'.
EDIT: line if((int)fin.tellg() <= 0){ really causes problems if the file is too large (> 2 GB) because tellg does not just return the number of characters from the beginning of the file (the tellg () function gives the wrong file size? ). It might be better to try separately to start the fin.tellg()==tellgValueForStartOfFile and for fin.tellg()==-1 errors. tellgValueForStartOfFile is probably 0, but the best way to make sure is probably the following:
fin.seekg (0, is.beg); tellgValueForStartOfFile = fin.tellg();
Joost Huizinga
source share