0

So I have a text file:

Dylan
6

where Dylan is the player name, and 6 is high score. I want to make it write a new player high score, but when I do it, it overwrites what I already have.

(here is the rest of my code if you wanna see it)

cin >> chName;
ofstream myfile;
myfile.open("score.txt");
myfile << chName << "\n" << iScore << "\n\n";
myfile.close();

How would I make it skip over what is already written? (also have it do this in the future)

I am very new to C++, so sorry if my question is vauge

Thanks

squid1
  • 5
  • 5
  • You mean append.- there is a flag to do this in fstream – Ed Heal Mar 14 '15 at 08:01
  • 1
    This is probably a duplicate of http://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c. In case you are looking for something different, please adjust your question :) – raute Mar 14 '15 at 08:02

3 Answers3

1

You can open the file for append operations, by simply using something like:

std::ofstream hiScores;
hiScores.open ("hiscores.txt", std::ios_base::app);

However, from a user rather than technical point of view, it's far more usual to have a limited high score table (say, ten entries). In that case you probably want to open it for read/write, read in the current high scores, adjust an in-memory structure to modify it, then write it back.

That would allow you to keep the high score table limited, pre-sorted for read and easily updatable. Though not necessary, I'd tend to use one line per player as well, just so the file is easily readable by humans:

Jon Skeet           759
Darin Dimitrov      576
BalusC              549
Hans Passant        530
Marc Gravell        526
VonC                476
CommonsWare         451
SLaks               436
Greg Hewgill        401
paxdiablo           387
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
  • I am currently working on sorting the list, but I don't really need it to be easily read by humans, because I have a scoreboard viewer within the program – squid1 Mar 14 '15 at 23:34
0

You should append to the file: (ios::app)

ofstream myfile;
myfile.open ("myfile.txt", ios::out | ios::app);
if (myfile.is_open())
{
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
}

http://www.cplusplus.com/doc/tutorial/files/

RvdK
  • 18,577
  • 3
  • 56
  • 100
0
filestr.open("filename.txt", fstream::in | fstream::out | fstream::app);

should append your new input to the file

samsun96
  • 168
  • 2
  • 13