This is my code for reading and Writing vectors; I get no errors while execution, but whenever I read back from it; it gives random values of integer instead of 50, and 100. What is it that I am doing wrong?
I have used vector objects inside of another object, and I am trying to file it using binary filing of objects.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Rest{
int value;
public:
void setvalue(int value){this->value=value;}
int getvalue(){return value;}
};
class Admin{
vector<Rest> restaurant;
public:
Admin(){}
void setValue(int value){
Rest obj1;
Rest obj2;
obj1.setvalue(value);
obj2.setvalue(value+50);
restaurant.push_back(obj1);
restaurant.push_back(obj2);
}
vector<Rest> getRestFromFile(){
Admin obj;
fstream getsavedvector("Testsave.BIN", ios::in | ios::binary);
getsavedvector.read(reinterpret_cast<char*> (&obj), sizeof(obj));
getsavedvector.close();
return obj.getRest();
}
void setRestVectorToFile(Admin obj){
fstream savevector("Testsave.BIN", ios::out | ios::binary);
savevector.write(reinterpret_cast<char*> (&obj),sizeof(obj));
savevector.close();
}
void setRestVector(vector<Rest> restaurant){
for(int i=0;i<restaurant.size();i++){
this->restaurant.push_back(restaurant[i]);
}
}
vector<Rest> getRest(){
return this->restaurant;
}
void Display(){
for(auto v: restaurant){
cout<<v.getvalue()<<endl;
}
}
};
int main()
{
Admin obj;
obj.setValue(50);
obj.setRestVectorToFile(obj);
Admin obj2;
obj2.setRestVector(obj2.getRestFromFile());
obj2.Display();
}
Aucun commentaire:
Enregistrer un commentaire