Correct you got the opening of a file down now you just need to do the actual writing to the file.
First let me clarify, you want this format for your text file correct?
<tab><tab><tab><name>, <score>
<tab><tab><tab><name>, <score>
....
.... |
If so this is how you would go about accomplishing this. First let's go over opening up a text file and writing to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int main()
{
std::ofstream highScoreFile("highscores.txt");
// Always check to see if the file is open and for errors.
if (highScoreFile.is_open())
{
// If it is open we can do our writing to the file.
// Here is a example of this.
highScoreFile << "I am writing to the file!";
}
else
{
// If the file isn't open something went wrong. Point that out.
std::cout << "Something went wrong with opening the file!";
}
// After you are done with the file always close it.
highScoreFile.close();
}
|
It is quite easy to write to a file. It is just like writing to the console with
std::cout
.
Though a important thing to note is that when you use the default ofstream constructor (Like I did above) it is in truncate mode which means it will discard anything in the file already and start over. This is why everything is being deleted.
In order for that not to happen open you file like this.
std::ofstream HighScoreFile("highscores.txt", std::ofstream::out | std::ofstream::app);
or with
open("highscores.txt", std::ofstream::out | std::ofstream::app);
std::ofstream::out means you want to output to the file (Write to it) and std::ofstream::app means you want to append to the file (don't overwrite everything).
Here is some more about the different flags
http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
HighScoreFile.open(
Now next up we need to know how to get the formatting right on your text file. As mentioned before you want <tab><tab><tab><name>, <score> for the format I believe.
All you will need to do is write them to the file in that order. Here is some pointers for how to write tabs and newlines (Creates a new line) if you didn't know already.
<tab> = "\t"
<newline> = "\n"
So your format would be like this. playerName = the variable which holds the name, playerNumber is the variable which holds that players number.
highScoreFile << "\t\t\t" << playerName << ", " << playerNumber << "\n";
Hopefully that helps a bit. Let me know if you have any specific questions or if anything is confusing.