writing/reading a vector of objects

I have this class below

class Account
{
private:
string fname;
string lname;
double amount;

public:
Account()
{ }

Account(string f, string l, double a): fname(f),lname(l),amount(a)
{ }


void save(fstream& outfile)
{
outfile.write((reinterpret_cast<char*>(&amount)),sizeof(amount));

int fnamelength=fname.length();

outfile.write((reinterpret_cast<char*>(&fnamelength)),sizeof(fnamelength));
outfile.write(fname.data(),sizeof(fname));

int lnamelength=lname.length();

outfile.write((reinterpret_cast<char*>(&lnamelength)),sizeof(lnamelength));
outfile.write(lname.data(),sizeof(lname));
}


void upload(fstream& infile)
{
static char buffer[128];
infile.read((reinterpret_cast<char*>(&amount)),sizeof(amount));

int fnamelength;
infile.read((reinterpret_cast<char*>(&fnamelength)),sizeof(int));
infile.read(buffer,fnamelength);
buffer[fnamelength]='\0';
fname=buffer;

int lnamelength;
infile.read((reinterpret_cast<char*>(&lnamelength)),sizeof(int));
infile.read(buffer,lnamelength);
buffer[lnamelength]='\0';
lname=buffer;

}
};



Now I create say five objects of Account and then push then into a vector and displays them to make sure they were corrected entered which works fine.

vector<Account>list;


now i want to save the objects into a binary file with the code below.

fstream outfile("BASE.dat",ios::out|ios::app);
for(int x=0;x<list.size();x++)
list[x].save(outfile);

its runs correctly but i noticed that only the first object in the vector saved I also tried using arrays but the same thing.

I read the BASE.dat using another code below to view what was stored.

fstream infile("BASE.dat",ios::in);
vector<Account>view;
Account temp;

while(!infile.eof())
{
temp.upload(infile);
view.push_back(temp);
}

I now display the vector content.

for(int x=0;x<view.size();x++)
view[x].display();


and only the first object that was created initially is displayed showing that only it was stored and the rest was not.

Please Guyz I need your assistance on this. I am doing a project and this is what is tieing me down.


These lines:
1
2
3
void save(fstream& infile)
void upload(fstream& infile)
fstream outfile("BASE.dat",ios::out|ios::app);


should be:
1
2
3
void save(ostream& infile)
void upload(istream& infile)
ofstream outfile("BASE.dat",ios::binary|ios::app);


Why are you saving these to a binary file anyway? A flat text file would be much better.
Topic archived. No new replies allowed.