From MSDN
STD::stack::top[
^]:
The top function returns the topmost element of the stack. You should ensure that there are one or more elements on the stack before calling the top function.
Although your stack does exist it does not contain any entries, so a call to
top()
will throw an exception; and since you are not in a
try{}/catch{}
block your program crashes. If you change your
while{}
to a
do{}/while{}
you can ensure that the stack will always have at least one value before doing the test.