Reputation: 5
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
Upvotes: 0
Views: 1079
Reputation: 881113
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
Upvotes: 1
Reputation: 357
filestr.open("filename.txt", fstream::in | fstream::out | fstream::app);
should append your new input to the file
Upvotes: 0
Reputation: 19790
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/
Upvotes: 0