Read integers from input and store each integer into a vector until 0 is read. Do not store 0 into the vector. Then, output all values in the vector in reverse order, each on a new line.
This is the current code I used and for some reason it only outputs 2 or 3 values instead of all of them. Is there something I did wrong?
int main() {
unsigned int i;
int inputNum;
vector<int> vectorNum;
cin >> inputNum;
while (inputNum != 0) {
vectorNum.push_back(inputNum);
cin >> inputNum;
}
for (i = 0; i < vectorNum.size(); ++i) {
cout << vectorNum.back() << endl;
vectorNum.pop_back();
}
return 0;
}
>Solution :
With this:
for (i = 0; i < vectorNum.size(); ++i) {
cout << vectorNum.back() << endl;
vectorNum.pop_back();
}
the issue is that you are increasing i in the for loop, but decreasing the number of entries in the vector with pop_back(). Both things occurring will result in less items processed.
Instead of a for loop, use while() and the empty() member function:
while (!vectorNum.empty())
{
cout << vectorNum.back() << endl;
vectorNum.pop_back();
}