我正在阅读一个问题池文件,该文件具有问题类型、章节、值得多少分、问题和答案。这段代码正在检查最小和最大章节(来自用户输入)是否在范围内(来自未知大小的文件)。我知道它在向量的末尾添加了一条额外的线,这导致了错误,但是我该如何解决呢?代码是:
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();
}