【问题标题】:ifstream - Read last character two timesifstream - 读取最后一个字符两次
【发布时间】:2015-06-25 12:06:15
【问题描述】:

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

这是类

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

【问题讨论】:

标签: c++ ifstream


【解决方案1】:

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

类似:

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

【讨论】:

  • 好的 - 你的意思是我应该在 fin.get() 之后的 if 语句中调用 fin.fail() 然后在那里休息一下?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多