覆盖文件中的第一行,并在其后添加新行

问题描述 投票:0回答:2

我想在我的游戏中创建一个评分系统,它将保存每个玩家的个人得分(int Score)(字符串输入)以及每个玩家得分的总和(scoreTotal)。为此,我想将 ScoreTotal 保留在文件的第一行,并在每次调用该函数时覆盖它,然后在其后为每个玩家及其得分创建一个新行,我该怎么做?

这是我的代码(不起作用):

void saveScore(int scoreTotal, int score, string input) {
    scoreTotal += score;
    ofstream total("score.txt");
    if (total.is_open()) {
        total << scoreTotal;
    }
    total.close();

    ofstream scoreFile("score.txt", ios::app);
    if (scoreFile.is_open()) {
        scoreFile << endl << input << " : " << score;
    }
    scoreFile.close();
}

(输入3个玩家后,我得到了正确的总分数,但第二行只有第三个玩家)

c++ fstream
2个回答
0
投票

这里的问题是你每次都会覆盖该文件。要修复错误,您需要首先读取文件内的所有数据,然后才能修改分数。这是一个简单的代码:

void saveScore(int scoreTotal, int score, string input) {
    vector<string> scores;
    string line;
    ifstream scoreFileRead("score.txt");
    if (scoreFileRead.is_open()) {
        getline(scoreFileRead, line); //Skip the total score line
        while (getline(scoreFileRead, line)) {
            scores.push_back(line);
        }
        scoreFileRead.close();
    }

    scoreTotal += score;
    ofstream scoreFileWrite("score.txt");
    if (scoreFileWrite.is_open()) {
        scoreFileWrite << scoreTotal << endl;
        for (const string& scoreLine : scores) {
            scoreFileWrite << scoreLine << endl;
        }
        scoreFileWrite << input << " : " << score;
        scoreFileWrite.close();
    }
}

所以这应该可以解决你的问题。


0
投票

只有当新乐谱与之前的乐谱具有相同的位数和格式时,您尝试做的事情才能成功。

否则,如果新分数的位数较少,新行将比现有行短,从而留下旧数据的痕迹。

同样,如果新分数的位数更多,则新行将比现有行更长,并覆盖下一行的一部分。

要做你想做的事,你应该完整地读入原始文件,然后根据需要修改数据,然后完整地写出一个新文件。

否则,请勿对文件使用文本格式。使用二进制格式,那么无论其值如何,分数都不会改变字节大小,因此您可以简单地查找并覆盖分数的那些字节,而不会影响文件的其余部分。

© www.soinside.com 2019 - 2024. All rights reserved.