I'm trying to create a basic highscore system for a project I'm working on.
The problem I'm having is, although I write the names into my main they just overwrite the previous.
Currently I have this:
void ManagePoint::saveScore(string Name, int Score) { ofstream newFile("scorefile.txt"); if(newFile.is_open()) { newFile << Name << " " << Score; } else { //You're in trouble now Mr! } newFile.close(); }
and for testing I'm adding them like so:
runner->saveScore("Robert", 34322); runner->saveScore("Paul", 526); runner->saveScore("Maxim", 34322);
On load display all that will appear is Maxim's score, how can I loop through and save them all, or append all or something?
Using ofstream with the "current file" name as parameter for the constructor will overwrite it.
Usually, every mode that entails writing to the file is meant to create a new file if the given filename does not exist. Thus, we need to call the open built-in function of std::fstream to create a new file with the name provided as the first string argument.
fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient. In particular, it's not a “best practice” and it's not necessary to flush the output.
You need to open the file with the append mode:
ofstream newFile("scorefile.txt", std::ios_base::app);
There are various other modes too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With