Question

when i run this code everything goes fine when writing , but when i press 2 to read it goes well and read everything just fine but when it it finishes reading the file (show function) it pops up a problem says " Unhandled exception at 0x5DF9CCC8 " with break , continue options . from my searching i think the problem comes from a pointer points to Null , but i don't know how to resolve it . here is the code

class person{
public :
string name;
int id ;
int age ;
void person :: show();
void person :: add_menue();
void person :: insert_data();
void person :: show_data();
};

person personobject;
  void person :: add_menue()
{
    cout << "Please Enter Name ID Age :" << endl;
    cin >> name >> id >> age ;
}

ofstream file;
void person::show()
{
    cout<<"Age  => "<<age<<endl;
    cout<<"Name => "<<name<<endl;
    cout<<"ID   => "<<id<<endl;
}

void person :: insert_data()
{
    ofstream file;
    file.open("binary.dat",ios::app| ios::binary);
    personobject.add_menue();
    file.write((char*)&personobject, sizeof(personobject));
    file.close();
}

void person :: show_data()
{
    ifstream file;
    file.open("binary.dat",ios::in| ios::binary);
    if(!file)
    {
        cout<<"File not Found";
    }
    else
    {
        file.read((char*)&personobject, sizeof(personobject));
        while(!file.eof())
        {
            personobject.show();
            cout<<"Press Any Key....For Next Record"<<endl;
            getchar();
            file.read((char*)&personobject, sizeof(personobject));
            }
    }
    file.close();
}

void main ()
{
    int choice;
    cout << "1 - to write \n2 - to  read" << endl;
    cin >> choice;
    if (choice==1)
    {
        person f;
        f.insert_data();
    }
    if (choice==2)
    {
        person a;
        a.show_data();
        system ("pause");
    }
}
Was it helpful?

Solution

Because you are using a string object instead of a plain character array, you can't just type cast the whole class to a char* and write it to the file (which in itself is a poor way of doing it. What if you changed around the order of the parameters and tried loading an older file?).

In your insert_data function, write each variable individually instead of casting the entire class. You could write the age and id first and you know that would take up 8 bytes, so whatever is remaining is the size of the name which can be loaded back into the string object in your read_data function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top