C++ fstream overwrite instead of append

为君一笑 提交于 2019-12-20 16:35:47

问题


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.



来源:https://stackoverflow.com/questions/15056406/c-fstream-overwrite-instead-of-append

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!