I'm reading in a file that is a question pool that has the type of question, chapter, how many points it is worth, the question and the answer. This bit of code is checking to see if the min and max chapters(from user input) are in range(from a file of unknown size). I know that it adds an extra line at the end of the vector, which is causing the error, but how can I fix it? The code is:
void checker(int min, int max, string file) {
ifstream myfile;
string line;
vector<int> numlist;
myfile.open(file);
while (myfile.is_open()) {
if (!getline(myfile, line)) {
break;
} else {
vector<string> chap = split_string(line);
int chapter = str2int(chap[2]);
numlist.push_back(chapter); //This is where the error is. Makes vector go out of range.
}
}
int small = 1000;
int large = 0;
for (size_t i = 0; i < numlist.size(); i++) {
if (numlist[i] < small) {
small = numlist[i];
}
}
for (size_t i = 0; i < numlist.size(); i++) {
if (numlist[i] > large) {
large = numlist[i];
}
}
if (min > max) {
cout
<< "Error: Please enter a number lower than or equal to the maximum chapter: "
<< endl;
cin >> min;
cout << endl;
} else if (min < small) {
cout
<< "Error: Please enter a number bigger than or equal than the minimum chapter ("
<< small << "): " << endl;
cin >> min;
cout << endl;
} else if (max > large) {
cout
<< "Error: Please enter a number bigger than or equal than the maximum chapter ("
<< large << "): " << endl;
cin >> max;
cout << endl;
}
myfile.close();
}