Исключение основного дампа - PullRequest
0 голосов
/ 05 декабря 2009

Я успешно скомпилировал этот код, но когда я дохожу до последнего цикла for в основном, я получаю дамп ядра handle_exception. Как мне это исправить?

main.cpp

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "DRSequence.h"
using namespace std;

vector <DRSequence> array;

int indexOfSequenceWithFirstWord(string word){
    for(unsigned int cnt=0;cnt<array.size();cnt++){
        DRSequence s = array[cnt];
        if(word.compare(s.firstWord())==0)
            return cnt;
    }
    return -1;

}


int main(int argc, char **argv) {

    cout << "Opening File:" <<  argv[1] << "\n";


    string in;
    ifstream inFile;
    inFile.open(argv[1]);
    if (!inFile) { cout << "Unable to open file"; exit(1); }

    unsigned int cnt = 0;
    DRSequence sequence;

    while (inFile >> in) {
        if(cnt % 2 == 0){
            int index = indexOfSequenceWithFirstWord(in);
            if(index<0){
                sequence.setFirstWord(in);
                array.push_back(sequence);
            }else
                sequence = array[index];

        }
        cnt++;
    }
    inFile.close();


    for(cnt=0;array.size();cnt++){
        DRSequence s = array[cnt];
        s.description();
    }

    return 0;
}

DRSquence.h

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class DRSequence {
    string first;
    vector <DRSequence> array;
    int count;
  public:

    void description(){
        cout << first << "\n"; 
        for(unsigned int cnt=0;cnt < array.size(); cnt++){
            cout << "\t" << array[cnt].firstWord() << " " << array[cnt].countDegree() << "\n";
        }
    }

    void setFirstWord(string s1){
        first = s1;
    }
    string firstWord(){
        return first;
    }

    int countDegree(){
        return count;
    }

    void addSecondWord(string s){

    }


  private:

    int indexOfSequenceWithWord(string word){
        for(unsigned int cnt=0;cnt < array.size();cnt++){
            DRSequence s = array[cnt];
            if(word.compare(s.firstWord())==0)
                return cnt;
        }
        return -1;
        }


};

1 Ответ

4 голосов
/ 05 декабря 2009

Ваш тест цикла for неверен:

for(cnt=0;array.size();cnt++){

Если в массиве есть какие-либо элементы, условие array.size() всегда будет иметь значение true, и оно будет циклически выполняться вечно, где forever означает «до тех пор, пока array[cnt] не выйдет за конец массива, и вы не получите нарушение доступа. «

Ты имеешь в виду нечто большее:

for(cnt=0; cnt < array.size(); ++cnt) {
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...