In fact, that code is guaranteed to fail at some point on at least three different levels.
You must allocate space for strings before you use them. But as
QWERTYman suggested, you would simply be better off using a std::string.
Also, use << for output, and >> for input.
It might be worth your while to read and write to a deque of high scores:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <deque>
#include <fstream>
#include <string>
using namespace std;
struct highscore
{
string name;
unsigned long score;
};
istream& operator >> ( istream& ins, highscore& hs )
{
ins >> hs.score;
ins >> skipws;
getline( ins, name );
return ins;
}
ostream& operator << ( ostream& outs, const highscore& hs )
{
outs << hs.score << ' ' << hs.name << endl;
return outs;
}
deque <highscore> ReadHighScores( const string& filename )
{
deque <highscore> result;
ifstream file( filename.c_str() );
highscore hs;
while (file >> hs)
result.push_back( hs );
file.close();
return result;
}
void WriteHighScores( const string& filename, deque <highscore> scores )
{
ofstream file( filename.c_str(), ios::trunc );
for (deque <highscore> ::iterator hs = scores.begin(); hs != scores.end(); hs++)
file << *hs;
file.close();
}
|
Surely this is much more convenient. :-)
[edit] BTW, the above code is simplistic. It doesn't account for the possibility that
name is the empty string, in which case the >> operator would fail.