-1

делаю программу-журнал, с данными студентов. Реализовал операции считки и записи данных в файл Программа работает корректно, все операции выполняет, но в конце своей работы вылетает исключение Вызвано исключение: нарушение доступа для чтения. _Pnext было 0x15E03CC. Все данные записываются корректно, и считываются тоже, просто конец выполнения программы = аварийный.

    #include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

class Table
{
    

};
class Student
{
public: Student(string sn, string snb, string sad, string mn, string mnb, string mad, string fn, string fnb, string fad)
    {
        this->student_name = sn;
        this->student_number = snb;
        this->student_address = sad;
        this->mother_name = mn;
        this->mother_number = mnb;
        this->mother_address = mad;
        this->father_name = fn;
        this->father_number = fnb;
        this->father_address = fad;
    }
public: Student()
{
    this->student_name = "0";
    this->student_number = "0";
    this->student_address = "0";
    this->mother_name = "0";
    this->mother_number = "0";
    this->mother_address = "0";
    this->father_name = "0";
    this->father_number = "0";
    this->father_address = "0";
}
public:
    string mother_number;
    string father_number;
    string student_number;
    string student_name;
    string mother_name;
    string father_name;
    string student_address;
    string mother_address;
    string father_address;
    void print()
    {
        cout << "Student name is " << student_name << "\nStudent number is " << student_number << "\nStudent address is " << student_address << "Student's mother's name is " << mother_name << "\nStudent's mother's number is " << mother_number << "\nStudent's mother address is " << mother_address << "Student's father's name is " << father_name << "\nStudent's father's number is " << father_number << "\nStudent's father's address is " << father_address << "\n";
    }

};
class event
{
    string name;
    string date;
};


int main()
{
    cout << "Individual project by Maxim Shevchuk IPZ-12_1\n";
    vector<Student> st_list;
    string path = "data.txt";
    Student st;
    ifstream fin;
    fin.open(path, ifstream::app);
    if (!fin.is_open())
    {
        cout << "Can't open file\n";
    }
    else
    {
        cout << "File was open, now we can edit it\n";
        while (fin.read((char*)&st, sizeof(Student)))
        {
            fin.read((char*)&st, sizeof(Student));
            st_list.push_back(st);
        }
        fin.close();
    }
    
    while (true)
    {
        cout << "What do you wand to do:\n1 - is add information about student\n2 - is find full information about student\n-3 - is edit information about student\n4 - is delete information about student\n";
        short choice;
        cin >> choice;
        if (choice == 1)
        {
            cout << "Lets enter all known information about the student\nTo begin with enter student's name, if you dont know - write: nothing\n";
            string sn;
            cin >> sn;
            cout << "Now enter his number, if you dont know - write: nothing\n";
            string snb;
            cin >> snb;
            cout << "Now enter his address, if you dont know - write: nothing\n";
            string sad;
            cin >> sad;
            cout << "Now lets enter all known information about his parents, lets start from student's mother\nEnter name of student's mother, if you dont know - write: nothing\n";
            string mn;
            cin >> mn;
            cout << "Now enter mother's number, if you dont know - write: nothing\n";
            string mnb;
            cin >> mnb;
            cout << "Now enter mother's address, if you dont know - write: nothing\n";
            string mad;
            cin >> mad;
            cout << "Now lets enter all known information about student's father\nLets start from name, if you dont know - write: nothing\n";
            string fn;
            cin >> fn;
            cout << "Now enter father's number, if you dont know - write: nothing\n";
            string fnb;
            cin >> fnb;
            cout << "Now enter father's address, if you dont know - write: nothing\n";
            string fad;
            cin >> fad;
            Student std(sn, snb, sad, mn, mnb, mad, fn, fnb, fad);
            st_list.push_back(std);
            break;
        }
        break;
    
    }
    ofstream fout;
    fout.open(path, ofstream::app);
    if (!fout.is_open())
    {
        cout << "Can't open file\n";
    }
    else
    {
        cout << "File was open, now we can edit it\n";
        for (int a = 0; a < st_list.size(); a++)
        {
            fout.write((char*)&st_list[a], sizeof(Student));
        }
    }
    fout.close();
    
}
1
  • fin.read((char*)&st, sizeof(Student)) что за хрень? Что Вы хотели сделать? Student не является POD типом, его побитовое копирование и/или инициализация до добра не доведёт.
    – Serge3leo
    4 ноя 2021 в 6:40

1 ответ 1

1

все операции выполняет, но в конце своей работы вылетает исключение

Основная проблема в том, что Student не является POD типом.

При операции fout.write((char*)&st_list[a], sizeof(Student)) в файл записывается не сама информация, а указатели на неё.

При операции fin.read((char*)&st, sizeof(Student)) считается не информация, а указатели. Поскольку дело происходит в том же самом приложении, то чтение информации полей класса всё равно проходит.

Однако, когда дело доходит до деструкторов, то некоторые части string и др., начинают повторно удаляться, что и вызывает исключение.

P.S. Но и сделать его POD типом тоже, хотя и будет работать, но нехорошо, некошерно. По-хорошему, Student надо преобразовывать в транспортное (сетевое) представление, например, JSON.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.