'Saving and Sorting Game Information Into an External File
I have this Blackjack card game (simple text-only console application) that I have been working on and currently I am trying to improve the way it stores the statistics in an external .txt file. I have been learning and messing around with fstream stuff and I got it to write the statistics into the external file: How the statistics are saved in a .txt file.
Now I would like to improve the system so that it sorts the players' entries according to the win ratio. I basically need to read a value from a specific spot in each existing entry (win ratio), compare them, and insert the new entry to the correct spot according to the value. Each entry has the same format as shown in the picture. Then after the .txt file has been sorted, I just need to basically read it and display it in the console.
I am pretty inexperienced with using fstream stuff and manipulating files in general so I would really appreciate some direction with what is the most efficient way to do this. I have thought of several ways of reading and comparing the win ratios but I can't think of a good way to separate each player's entry and to insert the new entry into the corresponding spot.
Here is how the current code of the saving system works, in case it is useful:
void saveGame() {
string playerName = {};
getline(cin, playerName);
fstream savefile;
savefile.open("Blackjack_Statistics.txt", fstream::app);
if (savefile.is_open()) {
savefile << "\n ---~~=[ " << playerName;
if (playerName[playerName.size() - 1] == 's') {
savefile << "' ";
} else {
savefile << "'s ";
}
savefile << "Statistics ]=~~---\n\n\t[Hands won]: " << countWins << "\n\t[Hands lost]: " << countLosses << "\n\t[Hands pushed]: " << countPushes << "\n\t[Hand win ratio]: ";
if (countLosses > 0) {
savefile << (countWins / countLosses);
} else {
savefile << (countWins / 1);
}
savefile << "\n\n\t[Blackjacks]: " << countBlackjacks << "\n\t[Dealer blackjacks]: " << countDealerBlackjacks << "\n\t[Double downs won]: " << countDouble << "\n\t[Longest win streak]: " << countStreakLongest << "\n\n";
} else {
cout << "Saving failed!";
}
savefile.close();
return;
}
Thanks! :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
