Reputation: 1165
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
Upvotes: 1
Views: 1504
Reputation: 5230
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 ;
Upvotes: 3