ifstream - 读取最后一个字符两次

ifstream - Read last character two times

从文本文件中读取字符时,我不知道为什么最后一个字符被读取了两次?但是如果我在该行中插入一个新行,它就不再被读取两次。

这是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;
    }
};

这是文本文件的内容(没有换行符)

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

和输出:

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

您需要在 fin.get 之后检查 fin。如果此调用失败(就像在最后一个字符上发生的那样)你继续前进,尽管流已经结束(并且 my_character 无效)

类似于:

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