0

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();

}
PhilMasteG
  • 3,095
  • 1
  • 20
  • 27
  • Welcome to StackOverflow. `map<>` stores its data on the heap. Therefore, you cannot simply write the binary data out to a file (which will result in a bunch of pointers being written out) and then read it back in again. Well, you can, but the resulting map will most definitely be invalid. Please have a look at serialization techniques for STL containers. Have a look [here](https://stackoverflow.com/questions/4422399/serialization-of-stl-class), for example. – PhilMasteG Jun 02 '22 at 08:01
  • you can't read and write objects to a file with `reinterpret_cast` unless they are a POD type (which `std::map` and `std::string` aren't`), you need to serialise the data in some way, e.g write them as a CSV file – Alan Birtles Jun 02 '22 at 08:15

0 Answers0