I want to write the objects of class A having a map as data member into a file and read it. When i run the program for the first time it displays the data but the next time i run the program i am unable to read the data in the file back. Is there some other way i can store objects having maps as data members in a file?
This is my code:
#include<iostream>
#include<map>
#include<string>
#include<iterator>
#include<algorithm>
#include <set>
#include<vector>
#include<fstream>
using namespace std;
class A
{
map<string,string>sys;
public:
void add()
{
string s,s1;
cout<<"Enter string1"<<endl;
getline(cin,s);
cout<<"Enter string2"<<endl;
getline(cin,s1);
sys.insert(pair<string,string >(s,s1));
}
void display()
{
map<string,string>::iterator itr;
for(itr=sys.begin();itr!=sys.end();itr++)
{
cout<<itr->first<<'\n'<<itr->second<<endl;
}
}
};
void write() //wrting the object
{
fstream file;
file.open("fg.txt",ios::app|ios::out|ios::in);
A obj;
obj.add();
file.write(reinterpret_cast<char*>(&obj),sizeof(obj));
file.close();
}
void read() //function to read the objects stored and retrive map data
{
fstream file;
file.open("fg.txt",ios::app|ios::out|ios::in);
A obj;
file.seekg(0);
while(file.read(reinterpret_cast<char*>(&obj),sizeof(obj)))
obj.display();
file.close();
}
int main()
{
write();
read();
}