使用fstream附加到文件,而不是覆盖

问题描述 投票:27回答:1

我正在尝试为我正在研究的项目创建基本的高分系统。

我遇到的问题是,尽管我将名称写到主名称中,但它们只会覆盖前一个名称。

目前我有这个:

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();

}

为了进行测试,我将它们添加为:

runner->saveScore("Robert", 34322);

runner->saveScore("Paul", 526);

runner->saveScore("Maxim", 34322);

在加载显示时,将显示的只是Maxim的得分,我该如何循环浏览并保存所有得分,或追加全部或其他内容?

c++ file overwrite
1个回答
42
投票

您需要使用附加模式打开文件:

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

也有various other modes

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