1

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
java
  • 1,165
  • 1
  • 25
  • 50
  • 2
    possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Baum mit Augen Jun 25 '15 at 12:11

1 Answers1

3

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 ;
marom
  • 5,064
  • 10
  • 14
  • ok - you mean that I should call fin.fail() in a if-statement after fin.get() and then put a break there? – java Jun 25 '15 at 12:18