【问题标题】:Ofstream adds blank line to end of fileOfstream 将空行添加到文件末尾
【发布时间】:2014-04-08 00:15:05
【问题描述】:

我希望有办法解决基本问题。当我使用 ofstream 在我的 c++ 中写入文件时,它会在末尾添加一个空行。有没有办法阻止这种行为?下次运行程序时加载文件时会导致问题。

int saveScores(scoreboard sBoard, const string filename) {
    ofstream outStream;
    outStream.open("/Users/Wescat/Desktop/Programming/comp2710/wsc0010_project1/scores.txt");
    if (outStream.fail()) {
        cout << "Output file opening failed." << endl;
        return 1;
    }
    int i = 0;
    while (i < sBoard.numOfScores) {
        outStream << sBoard.score->name << endl;
        outStream << sBoard.score->score << endl;

        sBoard.score = sBoard.score->next;
        i++;
    }
    outStream.close();
    return 0;
}

【问题讨论】:

  • 请将写入ofstream的代码贴出来。
  • 在您的代码中,最后写入的是来自std::endl 的换行符。

标签: c++ file ifstream ofstream


【解决方案1】:

这是完全合理的。

您解释为空行的内容正是您的文本编辑器表示在您的实际最后一行(由您的最终std::endl 生成)末尾存在\n 字符的方式。该角色的存在是有意义的,因为它是您所有行的所有的结尾。确实,这就是“行尾”的意思!

如果在您重新加载文件时这会导致问题,那么我建议您的真正错误确实存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2011-04-26
    • 2013-05-25
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多