I'm writing a program that reads and writes from a binary file, my problem is that although the file (for example) have 3 structs in it, it reads the last struct twice. this is my code:
the struct:
struct PARTICEPENTS
{
char id1[10];
char name1[11];
char id2[10];
char name2[11];
int points;
};
writing:
void EnterParticipants()
{
ofstream PartFile;
int i=1;
PARTICEPENTS part;
string temp="";
PartFile.open("part.bin",ios::out|ios::binary);
if(!PartFile){return;}
cout<<endl<<endl <<"Enter 3 Participants:"<<endl;
cout<<endl;
while(i<=3)
{
cout<<"the "<<i<<" couple"<<endl;
cout << "\tInsert the first id: " ;
getline(cin, temp);
strcpy(part.id1,stToChar(temp));
cout << "\tInsert the first name: ";
getline(cin, temp);
strcpy(part.name1,stToChar(temp));
cout << "\tInsert the second id:";
getline(cin, temp);
strcpy(part.id2,stToChar(temp));
cout << "\tInsert the second name:" ;
getline(cin, temp);
strcpy(part.name2,stToChar(temp));
part.points=0;
PartFile.write((char*)(&part), sizeof(part));
i++;
}
PartFile.close();
}
reading:
void DisplayFile()
{
ifstream PartFile;
PartFile.open("part.bin",ios::in|ios::binary);
PARTICEPENTS filePart;
if(!PartFile){return;}
while(!PartFile.eof())
{
PartFile.read((char*)(&filePart), sizeof(filePart));
cout<<left<<setw(12)<<filePart.id1<<left<<setw(12)<< filePart.name1
<<left<<setw(12)<<filePart.id2<<left<<setw(12)<<filePart.name2<<
left<<setw(7)<< filePart.points <<endl;
}
}
When I enter:
111111111 Kim 111111111 Lori
222222222 Roy 222222222 Tom
333333333 Guy 333333333 Don
the output to the screen is:
111111111 Kim 111111111 Lori 0
222222222 Roy 222222222 Tom 0
333333333 Guy 333333333 Don 0
333333333 Guy 333333333 Don 0
I have no idea why the reading doesn't stop after the last struct. Thanks for your help. (sorry for my bad English...)