Reputation: 63
I'm having a little trouble understanding why this code does not output as I expected? Any ideas?
Output: ? you are
Expected: ? you are how Hello,
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
stack<string> sentence;
sentence.push("Hello,");
sentence.push("how");
sentence.push("are");
sentence.push("you");
sentence.push("?");
for (int i=0; i<sentence.size(); ++i) {
cout << sentence.top() << " ";
sentence.pop();
}
cout << endl;
return 0;
}
Upvotes: 1
Views: 56
Reputation: 26419
Because calling sentence.pop() decreases stack size by 1 AND you're increasing i at the same time. You'll only get half of the values this way.
Do this instead:
while (!sentence.empty()){
cout << sentence.top() << " ";
sentence.pop();
}
Upvotes: 4
Reputation: 310980
When you issue pop() the size of the stack is decremented while variable i is increased independently of the size of the stack. I advice to substitute your loop for the following one
while ( !sentence.empty() ) {
cout << sentence.top() << " ";
sentence.pop();
}
Upvotes: 2
Reputation: 1143
When you're popping the stack inside the loop, you're changing it's size, affecting how many times the loop executes.
I would instead do:
while (!sentence.empty())
{
cout << sentence.top() << " ";
sentence.pop();
}
Upvotes: 0