have prepared a code in c++ to save high scores and it is working well when i compile it in turbo c++and run the code .

but when i exit from the turbo c++ , the file to which i saved the high scores get corrupted and so when i again takes the turbo c++ , the files which i have written to the file are all missing . please help me . here is the code

#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();
}

Opening the same file for input and output at the same time is not a good idea.

open for read
read it
close it
do stuff
open for write
write it
close it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.