ifstream - Read last character two times

1.4k views Asked by At

When reading chars from a textfile I dont know why the last character is read two times? But If I insert a new line to the row its no longer read two times.

Heres is the class

class ReadFromFile {

private:
    std::ifstream fin;
    std::string allMoves;

public:
    ReadFromFile(std::string fileName) {

        fin.open(fileName, std::ios::in);

        char my_character;
        if (fin) {
            while (!fin.eof()) {
                fin.get(my_character);
                allMoves += my_character;
            } 

        } else {
            std::cout << "file does not exist!\n";
        }

        std::cout << allMoves << std::endl;
    }
};

and heres the content of the textfile (without a newline)

 1,2 3,1 1,3 1,2 1,4

and the output:

 1,2 3,1 1,3 1,2 1,44
1

There are 1 answers

1
marom On BEST ANSWER

You need to check fin after fin.get. If this call fails (as it happens on last char) you keep going, despite the stream being over (and my_character invalid)

Something like:

fin.get(my_character);
if (!fin)
    break ;