Start New Discussion within our Software Development Community

Ok so a friend of mine came up with this code to create a highscores list for a game when i run it, it works perfect you can see everything fine. the problem comes when it tries to reopen the file again. The file has abunch of gibberish inside and doesnt work any ideas?

ive played with it a little but cant seem to find the problem.

#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<conio.h>

struct highscore {
char name[50];
int score;
};

main()
{
int i,j,tempscore,tempno;
char empty[]={"empty"};
ifstream fin("highscore.txt");
ofstream fout("highscore.txt");
highscore h[11];
j=0;
fin.seekg(0);
while (fin) {
fin.read((char*)&h[j],sizeof(highscore));
j++;
}
if (j==0) {
for (i=0;i<10;i++) {
strcpy(h[i].name,empty);
h[i].score=0;
}
}
fin.close();
cout<<"enter the name\n";
cin.getline(h[10].name,50);
cout<<"enter the score\n";
cin>>h[10].score;
tempscore=0;
for (i=0;i<10;i++) {
tempscore=0;
for (j=i;j<11;j++) {
if (h[j].score>=tempscore) {
tempscore=h[j].score;
tempno=j;
}
}
char name[50];
int p;
p=h[i].score;
h[i].score=h[tempno].score;
h[tempno].score=p;
strcpy(name,h[i].name);
strcpy(h[i].name,h[tempno].name);
strcpy(h[tempno].name,name);

}
fout.seekp(0);
for (i=0;i<10;i++)
{
fout.write((char*)&h[i],sizeof(highscore));
cout<<h[i].name<<"\t\t\t\t"<<h[i].score<<"\n";
}
fout.close();
getch();
}
This article has been dead for over six months. Start a new discussion instead.