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

时间:2015-06-25 12:06:16

标签: c++ ifstream

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

Heres是班级

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

1 个答案:

答案 0 :(得分:2)

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

类似的东西:

fin.get(my_character);
if (!fin)
    break ;
相关问题