I want to make a score system in my game that will save the individual score (int score) of every player (string input) as well as the sum of every player score (scoreTotal). To do that I want to keep the scoreTotal in the first line of the file and overwrite it every time the function is called, and then after it, create a new line for each player and his score, how do I do that?
Here is my code (not working):
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();
}
(after inputting 3 players I get the totalScore correctly but there is only the third player on the second line)
the problem here is that you override every time the file. To fix your bug, you need to read first all the data inside the file, and then you can modify the score. Here is a simple code:
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();
}
}
So this should fix your problem.