|
-
Jun 1st, 2003, 02:12 PM
#1
Thread Starter
Lively Member
Data File for score
I need some help with this part of a BATTLE SHIP program for school. The data file has to have their name and score. What i want to know is how to make the data file, display it correctly, how to sort the players according to the score and how to write to the file if the player has a high score. Its only the top 3 scores that i need to display. I think its C++6 im not sure though.
Can someone help me?
-
Jun 2nd, 2003, 02:38 AM
#2
C++ has no version numbers. You probably mean that you're using the IDE Microsoft Visual C++ 6.0.
Aaaanyway...
You could store the highscores in a struct or a class. I will use a struct for now.
Code:
// highscore.h
#ifndef _HIGHSCORE_H_
#define _HIGHSCORE_H_
#include <string>
struct highscore
{
int score;
std::string name;
// comparison operators
bool operator <(const highscore &o) const {
return score < o.score;
}
bool operator <=(const highscore &o) const {
return score <= o.score;
}
bool operator >(const highscore &o) const {
return score > o.score;
}
bool operator >=(const highscore &o) const {
return score >= o.score;
}
bool operator ==(const highscore &o) const {
return score == o.score;
}
bool operator !=(const highscore &o) const {
return score != o.score;
}
};
#endif
The easiest way to store the high scores would be a simple text file like this:
score name
Code:
100000 dummy
90000 smudo
80000 yuppie
reading in C++:
read a line, seperate score and name and store them
Code:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using std::ifstream;
using std::string;
using std::getline;
using std::set;
using std::istringstream;
#include "highscore.h"
void read_scores(ifstream &in, set<highscore> &scores)
{
highscore ths;
string ts;
istringstream iss;
while(in.good())
{
getline(cin, ts);
ths.name = ts.substr(ts.find_first_of(' ')+1);
iss.str(ts);
iss >> ths.score;
scores.insert(ths);
}
}
Displaying and writing are nearly the same, except that you'll want to display the name first and write the score first.
The nice thing about a set is that it sorts automatically, you don't need to do anything. You should notice, however, that unless you explicitly tell it otherwise it will sort using the less functional object, that means they will be in the reverse direction. You can overcome this problem easily by using rbegin, rend and reverse_iterator for iteration.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|