Append to a File with fstream Instead of Overwriti

2020-05-30 03:13发布

问题:

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?

回答1:

You need to open the file with the append mode:

ofstream newFile("scorefile.txt", std::ios_base::app);

There are various other modes too.