Here, I'll get you started. All of the below can be found out quite easily through http://www.cplusplus.com/reference/
If you know enough of the basic language, the above reference is a great way to expand your knowledge.
Code:
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <fstream>
struct Score {
// The fields of our score
std::string strName;
float fScore;
// Default constructor
Score() {
fScore = 0.0f;
}
// Comparison operator for std::sort()
bool operator>(const Score &clScore) const {
return fScore > clScore.fScore;
}
};
// Let's define stream operations for Score to make it easier to read and write ... oh and let's suppose strName is one word for simplicity (otherwise we need to use std::getline())
// First output streams (e.g. std::cout)
std::ostream & operator<<(std::ostream &os, const Score &clScore) {
return os << clScore.strName << ' ' << clScore.fScore;
}
// Now input streams (e.g. std::cin)
std::istream & operator>>(std::istream &is, Score &clScore) {
return is >> clScore.strName >> clScore.fScore;
}
// ...
// Now, then let's say you filled this up already
std::vector<Score> vScores;
// Sort these in ascending order ...
std::sort(vScores.begin(), vScores.end(), std::greater<Score>());
// Now, these are sorted and can be saved
Saving can be done with a loop, or if you want to use STL, through std::copy and std::ostream_iterator (try these out for fun, look under <algorithm> and <iterator> ... though they're often lengthy to use). I'll demonstrate this with a loop since it's simpler.
Code:
std::ofstream scoreStream("Scores.txt");
for (size_t i = 0; i < vScores.size(); ++i)
scoreStream << vScores[i] << std::endl;
Reading can be done in a similar fashion. If you want to use STL, you can also use std::copy and std::istream_iterator, but you'll need std::back_inserter too (it's quite goofy).
Code:
std::ifstream scoreStream("Scores.txt");
std::vector<Score> vScores;
Score clScore;
while (scoreStream >> clScore)
vScores.push_back(clScore);
For all of these examples, see the references for the included headers above. Good luck. I practically gave you an answer. Try to come up with your own. I hope you learned something.
Bookmarks