【问题标题】:(c++) terminate called after throwing an instance of(c++) 在抛出一个实例后调用终止
【发布时间】:2015-09-25 01:50:46
【问题描述】:

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

等级.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

等级.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;
    }

编译器不显示任何错误或警告,因此很难找到错误。这是我第一次遇到这个问题。请帮我解决一下这个。谢谢。

【问题讨论】:

  • 您应该使用调试器找到错误,而不是依赖编译器为您完成。

标签: c++


【解决方案1】:

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

temp = temp.substr(mark+1);

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

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

【讨论】:

  • @Marco 介意将问题标记为已解决吗?不客气。
猜你喜欢
  • 2018-07-03
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多