When I run this code I am getting Acces violation error. Help me find the problem

-1

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
1

Output1:
Name=Ali
Age=19


Input2:
Khan
25
1

Output2:
Name=Ali
Age=19

Unhandled exception at 0x7AFADF58 (msvcp120d.dll) in Lab 5.exe: 0xC0000005: Access violation reading location 0x00CB4C7C.

Please help me to handle this problem.

c++
exception
runtime-error
fstream
binaryfiles
asked on Stack Overflow May 1, 2020 by Ali Khan

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0