Core Dump Exception
I've successfully compiled this code, but when I get around to the last for loop in the main, I get a core dump handle_exception. How do I fix this?
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;
}
};
Your for-loop test is incorrect:
for(cnt=0;array.size();cnt++){
If the array has any elements in it, the condition array.size()
will always evaluate to true and this will loop forever, where forever means "until array[cnt]
is past the end of the array and you get an access violation."
You mean something more along the lines of:
for(cnt=0; cnt < array.size(); ++cnt) {
精彩评论