的实例抛出后调用终止

(c++) terminate called after throwing an instance of

本文关键字:调用 终止 实例      更新时间:2023-10-16

我在程序'抛出'std::out_of_range "实例后调用终止'中遇到这个错误,下面是我的代码:

grade.h

    #ifndef GRADE_H_
    #define GRADE_H_
    #include <string>
    #include <iostream>
    using namespace std;
    class Grade
    {
        int mid_term, final;
        double total;
        public:
            Grade *next;
            Grade();
            Grade(int i_mid_term, int i_final);
            void readFile(string _file);
            void printList();
            void subString(string s);
            void Show();
            void addTail(Grade *q);
    };
    #endif

grade.cpp

#include "grade.h"
#include <stdlib.h>
#include <fstream>
Grade *tail;
Grade *head;
Grade::Grade(int i_mid_term, int i_final)
{
    mid_term = i_mid_term;
    final = i_final;
//  total = i_total;
}
Grade::Grade()
{
    head = tail = NULL;
}
void Grade::addTail(Grade *q)
{
        if (tail != NULL){
            tail -> next = q;
        }else{
            head = tail = q;
        }
        tail = q;
        q -> next = NULL;
}

void Grade::readFile(string _file)
    {
        ifstream fin;
        fin.open(_file.c_str());
        if(!fin.is_open())
        {
            cout<<"Can't read.n";
            exit(1);
        }
        else
        {
            string s = "";
            while (getline(fin, s))
            {
                subString(s);
            }
            fin.close();
        }   
    }
void Grade::printList()
    {
        Grade *q;
        cout<<"The grade list is:n";
        q = head;
        int i = 1;
        while (q != NULL)
        {
            cout<<"nGrade no: "<<i<<endl;
            q-> Show();
            q = q->next;
            i++;
        }
    }
void Grade::subString(string s)
    {
        int mid_term; 
        int final;
        string temp;
        // Mid
        int mark = s.find(":");
        mid_term = atoi(s.substr(0,mark).c_str());
//      cout << mid_term << endl;
        // Final 
        temp = temp.substr(mark+1);
        mark = temp.find(":");
        final = atoi(temp.substr(0, mark).c_str());
//      cout << final << endl;
        Grade *q = new Grade(mid_term, final);
        this -> addTail(q);
    }
void Grade::Show()
    {
        cout << mid_term << "-" << final << endl;
    }

编译器没有显示任何错误或警告,这使得很难找到错误。这是我第一次遇到这个问题。请帮我一下。谢谢。

@YePhIcK是正确的。这是一个运行时错误,而不是编译错误。可能的罪魁祸首是你在Grade::subString中的一个substr调用。我的钱在

temp = temp.substr(mark+1);

如果没有找到第一个冒号,将会导致问题。

查找错误的一种便宜的方法是将代码封装在try/catch (std::exception)中,并不断缩小范围,直到找到错误行。不过,调试器可能是更好的解决方案。