When I run this code for the first time, it was working fine. But when I run it second time I am getting a runtime error. I am beginner in programming. I don't know how to solve this problem. Please help me to solve this.
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
class Person
{
private:
string name;
int age;
public:
void setdata(string name, int age)
{
this->name = name;
this->age = age;
}
void getdata()
{
cout << "Name = " << name << endl;
cout << "Age = " << age << endl;
}
};
using namespace std;
int main()
{
Person a;
ofstream ali("outfile", ios::binary | ios::app);
string name;
int age;
cout << "Enter a name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
a.setdata(name, age);
ali.write((char*)&a, sizeof(Person));
ali.close();
ifstream qwe("outfile", ios::binary);
qwe.seekg(0, ios::end);
int endpoint = qwe.tellg();
int n = endpoint / sizeof(Person);
int number;
cout << "Which entry do you want to open? ";
cin >> number;
int position = (number - 1)*sizeof(Person);
qwe.seekg(position);
qwe.read((char*)&a, sizeof(Person));
a.getdata();
qwe.close();
system("pause");
return 0;
Input1:
Ali
19
1Output1:
Name=Ali
Age=19
Input2:
Khan
25
1Output2:
Name=Ali
Age=19Unhandled exception at 0x7AFADF58 (msvcp120d.dll) in Lab 5.exe: 0xC0000005: Access violation reading location 0x00CB4C7C.
Please help me to handle this problem.
User contributions licensed under CC BY-SA 3.0