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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15056406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:57:29  来源:igfitidea点击:

Append to a File with fstream Instead of Overwriting

c++fileoverwrite

提问by Springfox

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?

在加载显示时,所有将出现的是 Maxim 的分数,我如何循环并保存它们,或者附加所有内容或其他内容?

回答by Joseph Mansfield

You need to open the file with the append mode:

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

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

There are various other modestoo.

还有各种其他模式