Нужна помощь в разрешении необработанной ошибки исключения - PullRequest
0 голосов
/ 09 мая 2020

Я учусь программировать уже несколько месяцев и работаю над программой для управления данными студентов. Вот код:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <stdio.h>

using namespace std;

class Student
{
private:
    string name;
    string course;
    int section;
    int grade;

public:
    void calcgrade();
    void getData();
    void showData();

};

void Student::calcgrade() 
{
    if (grade >= 90)

        grade = 'A';

    else if (grade >= 80)

        grade = 'B';

    else if (grade >= 70)

        grade = 'C';

    else if (grade >= 60)

        grade = 'D';

    else

        grade = 'F';
}

void Student::getData() 
{
    cout << "Enter the name of the student: ";
    cin.ignore();
    getline(cin, name);

    cout << "Enter the course: ";
    cin >> course;

    cout << "Enter the section: ";
    cin >> section;

    cout << "Enter the grade received: ";
    cin >> grade;
    calcgrade();
}

void Student::showData()
{
    cout << ".......Student Information......" << endl;
    cout << "Student Name: " << name << endl;
    cout << "Course: " << course << endl;
    cout << "Section: " << section << endl;
    cout << "Grade: " << grade << endl;
    cout << endl;
}


void addData() 
{
    Student st; 
    ofstream fout; 
    fout.open("Student.data", ios::binary | ios::out | 
            ios::app); 
    st.getData(); 
    fout.write((char*)& st, sizeof(st)); 
    fout.close(); 
    cout << "Data Successfully Saved to File." << endl;
}

void displayData() 
{
    Student st;
    ifstream file;  
    file.open("Student.data", ios::in | ios::binary);

    if (file.is_open()) 
    {
        while (file.read((char*)& st, sizeof(st)))
        {
            st.showData(); 
        }

        cout << "Finished Reading Data From File." << 
                    endl;
    }
    else 
    {
        cout << "Unable to open file" << endl;
    }
    file.close();

}

void searchData()
{
    Student st;
    ifstream file;
    file.open("Student.data", ios::in | ios::binary);
    string search; 
    cout << "Please enter the first name of a student to search for: ";
    cin >> search;
    bool isFound = 0; 
    while (file.read((char*)& st, sizeof(st))) 
    {
        string temp = " ";
        getline(file, temp);
        for (int i = 0; i < search.size(); i++)
        {
            if (temp[i] == search[i])
                isFound = 1;
            else
            {
                isFound = 0;
                break;
            }
        }

        if (isFound) 
        {
            cout << "The name " << search << " was found in the database." << endl;
            break;
        }
    }

    if (file.read((char*)& st, sizeof(st)) && (!isFound)) 
    {
        cout << "Name not found." << endl;
    }

    file.close();
}

void modifyData() 
{
    Student st;
    string stname;
    bool isFound = 0; 
    int pos;
    fstream file;

    file.open("Student.data", ios::in | ios::out | ios::binary);

    cout << "Enter the name of a student whose data you want to modify: ";
    cin >> stname;

    while (file.read((char*)& st, sizeof(st))) 
    {
        string temp = " ";
        getline(file, temp);
        for (int i = 0; i < stname.size(); i++)
        {
            if (temp[i] == stname[i])
                isFound = 1;
            else
            {
                isFound = 0;
                break;
            }
        }

        if (isFound)
        {
            pos = file.tellg(); 

            cout << "Current Data" << endl;
            st.showData();
            cout << "Modified Data" << endl;
            st.getData();
            file.seekg(pos - sizeof(st)); 
            file.write((char*)& st, sizeof(st));
        }

    }

    if (file.read((char*)& st, sizeof(st)) && (!isFound)) 
    {
        cout << "Name not found." << endl;
    }

    file.close();
}

void deleteData()
{
    Student st;
    string stname;
    bool isFound = 0;
    ifstream file;
    ofstream fout;

    file.open("Student.data", ios::in | ios::binary);
    fout.open("Temporary.data", ios::out | ios::app | ios::binary);

    cout << "Enter the name of a student whose data you want to delete: ";
    cin >> stname;

    while (file.read((char*)& st, sizeof(st))) 
    {
        string temp = " ";
        getline(file, temp);
        for (int i = 0; i < stname.size(); i++)
        {
            if (temp[i] == stname[i])
                isFound = 1;
            else
            {
                isFound = 0;
                break;
            }
        }

        if (isFound)
        {

            cout << "Bleh" << endl;
            fout.write((char*)& st, sizeof(st));
        }
    }
    if (file.read((char*)& st, sizeof(st)) && (!isFound))
    {
        cout << "Name not found." << endl;
    }

    fout.close();
    file.close();

    remove("Student.data");
    rename("Temporary.data", "Student.data");
}
void printData()
{
    ifstream file;
    file.open("Student.data", ios::in | ios::binary);
    if (file.is_open())
    {
        cout << file.rdbuf();
    }

    file.close();
}

int main()
{
    int num;


    do
    {
        cout << "...............STUDENT MANAGEMENT SYSTEM..............\n";
        cout <<  "======================================== ==============\n";
        cout << "0. Close Program. " << endl;
        cout << "1. Add Data. " << endl;
        cout << "2. List Data. " << endl;
        cout << "3. Modify Data. " << endl;
        cout << "4. Search For Data. " << endl;
        cout << "5. Print Data. " << endl;
        cout << "6. Delete Data. " << endl;

        cout << "Choose an option: ";
        cin >> num;

        if (num == 1)
        {
            addData();
        }
        else if (num == 2)
        {
            displayData();
        }
        else if (num == 3)
        {
            modifyData();
        }
        else if (num == 4)
        {
            searchData();
        }
        else if (num == 5)
        {
            printData();
        }
        else if (num == 6)
        {
            deleteData();
        }
    } while (num > 0);

    return 0;
}

В идеале, когда программа запускается, пользователь выбирает вариант с различными вызовами функций в зависимости от введенного числа. Параметр «Добавить данные» работает нормально, но при выборе других параметров, таких как «Данные списка» или «Данные поиска», я сталкиваюсь с ошибкой, например: Возникло необработанное исключение: нарушение прав доступа на чтение. _Pnext был 0x10A6A04.

Код в xmemory:

 inline void _Container_base12::_Orphan_all() noexcept {
    #if _ITERATOR_DEBUG_LEVEL == 2
        if (_Myproxy != nullptr) { // proxy allocated, drain it
            _Lockit _Lock(_LOCK_DEBUG);

            for (_Iterator_base12** _Pnext = &_Myproxy->_Myfirstiter; *_Pnext != nullptr;
                *_Pnext = (*_Pnext)->_Mynextiter) {
                (*_Pnext)->_Myproxy = nullptr;
            }

            _Myproxy->_Myfirstiter = nullptr;
        }

Учитывая, что в коде нет очевидных ошибок, мне бы хотелось немного помочь в выяснении того, что я сделал неправильно.

...