I am a Grade 10 student taking a Computer Science course over the summer and I am having trouble with my homework question.
The question asks to write code that will allow a user to enter 6 grades and sort the grades into two different vectors; one that stores passing grades and another that stores failing grades (>=60 means you pass). In the end, it wants you to print all the passing and failing grades in their respective place (passing grades on one line, failing grades on the other).
So far, my code accepts the user's input and successfully stores it into an integer array with 6 elements. However, after accepting the input, this error shows up:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
signal: aborted (core dumped)
Please look at the snippet below:
int userGrades[6];
vector <int> passingGrades;
vector <int> failingGrades;
for (int i = 0; i < 6; i++) {
cout << "Enter the grades of Student " << i+1 << ": ";
cin >> userGrades[i];
}
for (int x = 0; x < 6; x++) {
for (int y = 0; y < 6; y++) {
if (userGrades[x] >= 60) {
passingGrades.at(x) = (userGrades[x]);
break;
}
else {
failingGrades.at(x) =(userGrades[x]);
break;
}
}
}
int pgSize = passingGrades.size();
int fgSize = failingGrades.size();
cout << "The passing grades are: ";
for (int a = 0; a < pgSize; a++) {
cout << passingGrades[a] << ", ";
}
cout << "The failing grades are: ";
for (int b = 0; b < fgSize; b++) {
cout << failingGrades[b] << ", ";
}
The vectors passingGrades
and failingGrades
have no elements, so any access to their "elements" are invalid.
You can use std::vector::push_back()
to add elements to a std::vector
.
Also note that the loop using y
looks meaningless because the code inside the loop doesn't use y
and executes break;
in the first iteration.
In conclusion, the part:
for (int x = 0; x < 6; x++) {
for (int y = 0; y < 6; y++) {
if (userGrades[x] >= 60) {
passingGrades.at(x) = (userGrades[x]);
break;
}
else {
failingGrades.at(x) =(userGrades[x]);
break;
}
}
}
should be:
for (int x = 0; x < 6; x++) {
if (userGrades[x] >= 60) {
passingGrades.push_back(userGrades[x]);
}
else {
failingGrades.push_back(userGrades[x]);
}
}