I made a program that writes a structure into a binary file, and then reads that binary file into a different variable. Writing into file and reading from it works fine, however the program crashes on exit.
I tried using the same variable for reading which works, but is not the solution I'm looking for. I want to know why the program crashes when I read structure from binary file into a different variable.
Here's the code:
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>
using namespace std;
struct t_student{
string name;
string lastname;
int mark;
};
int main(){
t_student student[30], student_read[30];
int n, i;
srand(time(0));
fstream dat("student.dat", ios::in | ios::out | ios::binary | ios::trunc);
cout << "Input number of students (up to 30): ";
cin >> n;
if(n > 30) n = 30;
cout << endl;
cin.ignore();
for(i = 0; i < n; i++){
cout << "Input first name: ";
getline(cin, student[i].name);
cout << "Input last name: ";
getline(cin, student[i].lastname);
student[i].mark = rand()%5+1;
cout << endl;
dat.write((char *) &student[i], sizeof(student[i]));
}
dat.clear();
dat.seekg(0);
i = 0;
while(!dat.eof()){
dat.read((char *) &student_read[i], sizeof(student_read[i]));
if(dat.eof()) break;
cout << endl << student_read[i].name << " " << student_read[i].lastname << " - " << student_read[i].mark;
i++;
}
dat.close();
cin.get();
//exit(0);
}
As you might notice, I also added exit(0) function, which prevents the program from crashing, but I want to know why the program crashes in the first place.
Thanks for your help.