Exception thrown while executing the code

-1
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <fstream>
#include <string>

using namespace std;

class student {
    int roll;
    string name;
    float marks;
    char result;
public:
    student() : roll(1), name("Student"), marks(0.0), result('F') {}

    void setDetails();
    void setResult();
    void showDetails();
};

void student::setDetails() {
    cout << "\nEnter details of student-------->" << endl;
    cout << "\nEnter Roll: ";
    cin >> roll;
    cin.ignore();
    cout << "\nEnter name: ";
    getline(cin, name);
    cout << "\nEnter marks: ";
    cin >> marks;
    setResult();
}

void student::setResult() {
    if (marks > 30) {
        result = 'P';
    }
    else {
        result = 'F';
    }
}

void student::showDetails() {
    cout << "\nDetails of student -------->" << endl;
    cout << "\nRoll: " << roll;
    cout << "\nName: " << name;
    cout << "\nMarks: " << marks;
    cout << "\nResult: " << result;
}

void readFromFile(student &st) {
    ifstream classDetails("class.dat", ios::in | ios::binary);
    classDetails.read((char*)&st, sizeof(st));
    st.showDetails();
}

void writeToFile(student &st) {
    cout << "\nObject received: ";
    st.showDetails();
    _getch();
    ofstream classDetails("class.dat", ios::out | ios::app | ios::binary);
    classDetails.write((char*)&st, sizeof(st));
    classDetails.close();
}


int main() {
    remove("class.dat");
    student st[3];

    for (int i = 0; i < 3; i++) {
        st[i].setDetails();
        system("cls");
        //st[i].showdetails();
        writeToFile(st[i]);
    }

    for (int i = 0; i < 3; i++) {
        system("cls");
        readFromFile(st[i]);
    }


    getch();
    return 0;

}
  1. I don't know why but an exception is generated after reading from the binary file.

    Exception thrown at 0x011FA398 in C++ Practice.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD.

  2. What is the difference between student &stand student st. I know '&' is used to pass as reference, but what difference it would have if I pass it without reference.
c++
exception-handling
asked on Stack Overflow Aug 7, 2018 by Akhil Singh • edited Aug 7, 2018 by Alan Birtles

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0