I'm working on a soccer management program
I had some other members of my group to compile data on 400 real life players into a text file.
I planned on reading the text file using a program ,converting individual players into objects and then writing them to another file (in binary mode) to be used by my program..
The reading and writing seems to have gone well, but when I try to open the new file containing the player objects, the program seems to be able to read only 20 players for some reason..
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
class plr
{
public:
int id;
int shirt_no;
int age;
int goals;
int pos;//0-GK,1-DEF,2-MID,3-ATT
char LName[51];
char FName[51];
int team;
int skill;
int goaltime;
int cards;
void transfer(int t_id)
{
team = t_id;
}
}plrs[401],plrs2[401];
fstream reader("players.txt", ios::in);
fstream binary("players2.dat", ios::out);
//READ FROM TEXT FILE into objects :
int j;
for (int i=1;i<=401;i++)
{
reader>>j;
plrs[j].id = j;
reader>>plrs[j].LName>>plrs[j].FName>>plrs[j].team>>plrs[j].shirt_no>>plrs[j].age>>plrs[j].pos>>plrs[j].skill>>plrs[j].goaltime>>plrs[j].cards;
cout << "\n\n";
}
reader.close();
//Display all players
for(int j=1;j<=400;j++)
{cout<<"\n\n"<<plrs[j].LName<<"\n"<<plrs[j].FName<<"\n"<<plrs[j].team<<"\n"<<plrs[j].shirt_no<<"\n"<<plrs[j].age<<"\n"<<plrs[j].pos<<"\n"<<plrs[j].skill<<"\n"<<plrs[j].goaltime<<"\n"<<plrs[j].cards;
}
//Write objects to file
for (int j=1;j<=400;j++){
binary.write((char*)&plrs[j], sizeof(plrs[j]));
}
binary.close();
//Read objects from that file through another filestream into a different array of objects
fstream plrreader("players2.dat", ios::in);
for (int j=1;j<=400;j++)
{
if (plrreader.read((char*)&plrs2[j], sizeof(plrs2[j])))
{
cout<<j<<" succesful\n";
}
}
cout<<"Read successful";
//Display objects -- some error here, only 20 players seem to be readable :
for (int j=1; j<400; j++)
{
cout<<"\n"<<plrs2[j].id<<"\nName :"<<plrs2[j].FName<<" "<<plrs2[j].LName<<"\nTeam :"<<plrs2[j].team<<"\n No.:"<<plrs2[j].shirt_no<<"\n Age:"<<plrs2[j].age<<"\n Pos :"<<plrs2[j].pos<<"\n Skill:"<<plrs2[j].skill<<"\n Max goals scored in"<<plrs2[j].goaltime<<"\n Cards"<<plrs2[j].cards;
}
plrreader.close();
return 0;
}
I'm reading from players.txt, storing players in an array of 'plr' objects (plrs).
This seems to be working as expected (all 400 players are displayed correctly)
Then I'm writing these objects using write() to players2.dat. This too, seems to be working (I opened the dat file in notepad, and it has all 400 players)
But when I open the newly created dat file and read the objects into another array of player objects (plrs2), only the first 20 players are read correctly.. The rest are displayed as zeroes..
I've also tried putting the part which reads the objects (line 65 onwards) into another .cpp file, but I get the same result.
I've attached the players.txt file, if anyone needs to run the code..
Please help..