void readGroups(ifstream &filein) {
vector<string> listOfStringTokens;
string tmpLine = "";
string tokens = "";
string courseCode, groupCode, groupName;
int minGroupSize = 0, maxGroupSize = 0;
int counter = 0;
while (filein.good()){
getline(filein, tmpLine);
istringstream iss(tmpLine);
while (!iss.eof()){
getline(iss, tokens, ';');
listOfStringTokens.push_back(tokens);
}
}
tmpLine = "";
tokens = "";
filein.close();
for (unsigned i = 0; i<listOfStringTokens.size(); i++){
courseCode = listOfStringTokens.at(i);
groupCode = listOfStringTokens.at(i+1);
groupName = listOfStringTokens.at(i+2);
minGroupSize = converter(listOfStringTokens.at(i+3), minGroupSize);
maxGroupSize = converter(listOfStringTokens.at(i+4), maxGroupSize);
cout << courseCode << "\t" << groupCode << "\t" << groupName << "\t"
<< minGroupSize << "\t" << maxGroupSize << "\t" << endl;
i += 4;
}
}
int converter(string a, int b) {
stringstream convert;
convert << a;
convert >> b;
convert.str("");
convert.clear();
return b;
}
Hi everyone!
It is almost the first time for me using vectors and now i get stuck with this. The source of my problem is the increase of unsigned i variable in the .at() in the for loop as i brought it to light. However i must make it to get an appropriate output. So i need your help guys to make this code run perfect without modifie the structure of output.
Here's the output how it looks like:
xxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxx xx xx
xxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxx xx xx
xxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxx x xx
invalid vector<T> subscript
1 Answer
You let i reach the largest number allowed to access the vector. The problem is you adding even more when calling "at".
Let's say that listOfStringTokens contains 12 Element. Imagine the last iteration: i<listOfStringTokens.size() is true and i is 11:
courseCode = listOfStringTokens.at(i);
This will work, because you access the index 11.
groupCode = listOfStringTokens.at(i+1);
This will not work, because i+1 yields an index that is out of bounds.
You also increment i in two different places:
for (unsigned i = 0; i<listOfStringTokens.size(); i++)
and here
i += 4;
This may cause you to lose oversight at a later point in time. Consider doing all incrementations in the first line.