第二次读取文件后c ++程序崩溃

c++ program crashing after reading a file the second time

基本上,问题已经在标题中描述了:第一次启动程序时(意味着然后创建了新文件),它运行完美并且没有崩溃,但是第二次尝试时(这意味着文件已经存在),它崩溃了。

问题是:为什么会崩溃?我该如何防止这种情况发生?

代码如下:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

class TStudent
{
public:
    string Name, Surname;
    int Age;

    TStudent(string name, string surname, int age)
    {
        Name = name;
        Surname = surname;
        Age = age;
        cout <<"\n";
    }

    string toString() const
    {
        return Name + " ; " + Surname + " ; " + to_string(Age);
    }

    int aux1 = sizeof(Name), aux2 = sizeof(Surname);
};


class TRegistru
{
public:
    string name, surname;
    int age;
    vector <TStudent> students;

    TRegistru(const TStudent &other)
    {
        this->name = other.Name;
        this->surname = other.Surname;
        this->age = other.Age;

        students.push_back(other);

    }

    void adauga(const TStudent& student)
    {
        students.push_back(student);
    }

    void salveaza(string file_name)// creating the file and storing the data
    {
        ofstream file1;
        file1.open(file_name, ios::app);
        file1.write((char*)&students, sizeof(students));
        file1.close();
        cout<<"\nFile saved and closed successfully.\n"<<endl;
    }

    void sterge()
    {
        students.clear();
    }

    void incarca(string file_name)// opening the file and reading the data
    {
        ifstream file2;
        file2.open(file_name, ios::in);
        if(!file2)
        {
            cout<<"Error in opening file..";
        }
        else
        {
            cout<<"File opened successfully.\n"<<endl;
        }
        file2.seekg(0);
        file2.read((char*)&students, sizeof(students));
    }

    void afiseaza()//printing the data
    {
        for(auto student : students)
        {
            cout << student.Name << endl ;
            cout << student.Surname << endl;
            cout << student.Age << endl;
            cout <<"\n";
        }
    }

    string toString() const
    {
        string ret{};
        for(const auto& student : students)
        {
            ret += student.toString() + "\n";
        }
        return ret;
    }


};

int main()
{
    TStudent student1("Simion", "Neculae", 21);
    TStudent student2("Elena", "Oprea", 21);
    TRegistru registru(student1);
    registru.adauga(student2);
    registru.salveaza("data.bin");// creating the file and storing the data
    registru.sterge();
    registru.incarca("data.bin");// opening the file and reading the data
    registru.afiseaza();//printing the data

    return 0;
}

第二次阅读您的代码后,我意识到您尝试读写向量的方式完全错误:

vector <TStudent> students;
...
    ifstream file2;
    file2.open(file_name, ios::in);
    file2.seekg(0);
    file2.read((char*)&students, sizeof(students)); // WRONG!!!

向量确实以连续的方式存储其数据,但向量的地址不是数据的地址。正确的方法是将vector的每个元素序列化到文件中,然后反序列化每个元素并将其推入vector。