问题
I'm having a problem in my code that results in a run time error. To debug the code I've thrown in some cout statements to find the last location that code executes properly. Based on the output it looks like the while statement breaks when the while condition evaluates to false, but I can't see how that's possible. Here's the code:
var declarations:
queue<string> newOrder;
stack< vector<char> > opStack;
char symbol;
stuff happens that populates the stack and queue, then this code is reached:
while(opStack.empty()==false){
if(opStack.top()[1] != 'L'){
cout<<"is stack empty?:"<<opStack.empty()<<endl;
symbol = opStack.top()[0];
newOrder.push(symbol);
opStack.pop();
cout<<"popped stack;"<<endl;
cout<<"is stack empty?:"<<opStack.empty()<<endl;
}
else{
break;
}
}
cout<<"made it out of while loop";
if(opStack.top()[1] == 'L'){
opStack.pop();
}
else{
errorEncountered = true;
}
this is the output:
is stack empty?:0
popped stack;
is stack empty?:1
RUN FAILED (exit value 1, total time: 1s)
So, based on the output, the stack is empty at the end of the loop. This should makes the while loop condition false, but the program fails before the while loop exits. How can that be possible? Does it have something to do with the way that stacks work?
回答1:
The while loop DOES exit on the false condition. I wasn't debugging properly, and that made me focus on the wrong part of the code.
The problem is actually what happens AFTER the last cout. The statement after that, if(opStack.top()[1] == 'L'){
, tries to get the top item from the empty stack and causes the run to fail.
But how is that possible, since we never see "made it out of while loop" in the output? It's because the last cout isn't ever flushed to the output before the program crashes. I added <<endl
to the last cout, and that did the trick. "made it out of while loop" was displayed and I was able to pinpoint the real problem in the program. (solved it by putting the last if-else statement inside if(opStack.empty()==false){//second if-else set}
)
Thanks to @interjay for pointing out that cout wasn't getting flushed in my original but poorly formatted question: c++ while loop condition isn't playing nice with stack.empty())
来源:https://stackoverflow.com/questions/13185457/c-while-loop-doesnt-exit-on-false-condition