-3

I was just wondering how to write a list in a csv for my dice game in C++

Here is what i have so far:

void csv_export1(int score)
{
    ofstream my_file;
    my_file.open("score.csv");
    my_file << USERNAME << "," << score <<"\n" << endl;
}


void csv_read()
{
    fstream fin;
    fin.open("score.csv");
}

Why does it write over the original score? Many thanks.

Thomas
  • 9
  • 1
  • 3
    You can fix this by setting the flags to append however my advice is open the file 1 time instead of reopening on each line. Related to appending: [https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c](https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c) – drescherjm Jan 18 '21 at 22:25
  • 2
    Sometimes it helps to re-read your question when you are done writing. In this case, you started with "how to write", but ended with "why overwrite". Since you've demonstrated the ability to write to a file, the latter seems to be your real question. So lead off with that. Try something more like *"I was wondering why, when I write to a csv file, I overwrite the original data instead of adding a new line."* – JaMiT Jan 18 '21 at 23:00

1 Answers1

1

By default, opening a file for output will truncate the it, overwriting its contents. std::ostream::open can take two arguments, the latter of which can be used to tell it to append data to the file, instead of this default behaviour. See this page for more details on what std::ios::out and std::ios::app are doing in the following example.

So, your program might look more like this:

void csv_export1(const int &score) {
    std::ofstream my_file;
    my_file.open("score.csv", std::ios::out | std::ios::app);
    my_file << "USERNAME" << "," << score << std::endl;
}

On another note, as has been mentioned elsewhere, this approach of opening the file each time the function is called can be costly. A more efficient approach might be to open the file elsewhere, and pass it to the function by reference.

Inigo Selwood
  • 822
  • 9
  • 20