mercredi 26 avril 2017

Reading and Writing to files using vector C++

I'm trying to create a function that reads User data types from file, stores it into a vector, pushes a new User into vector than sorts it and write the vector into the file. But it's not working.The function doesn't write anything.

void CreateAccount(){
string name,pass;
int acc_no;
double bal;
int i=0;
cout<<"Enter user's name:";
cin.ignore(256, '\n');
getline(cin, name, '\n');
cout<<"Enter user's password:";
cin>>pass;
cout<<"Enter user's account no:";
cin>>acc_no;
cout<<"Enter user's balance:";
cin>>bal;
fstream file;
User a(name,pass,acc_no,bal);
User u;
file.open("Data.dat",ios::binary|ios::out|ios::in|ios::app);
if(!file){
    cout<<"File could not be opened!"<<endl;
    return;
}
while(file.read(reinterpret_cast<char *>(&u),sizeof(User))){
        v.push_back(u);
}
v.push_back(a);
merge_sort(v,0,v.size()-1);
for(i=0;i<v.size();i++){
    u=v[i];
    file.write(reinterpret_cast<char*>(&u),sizeof(User));
}
file.close();
}

Aucun commentaire:

Enregistrer un commentaire