Stack functions

This is a discussion on Stack functions within the C++ Programming forums, part of the General Programming Boards category; Hi , I've been trying to write a program that will stack numbers in a row (while the number is ...

Stack functions

Hi , I've been trying to write a program that will stack numbers in a row (while the number is less than 9). The pop function which I've written is supposed to remove all of the elements that are more than 9 and list them as being popped. The problem I am having now is that I want to be able to "peek" into the stack before the numbers are "popped" and after they are "popped".
I've written the "peek" function but am unable to get the correct answer. It only returns one number in the current stack instead of all of them (before pop).
Also i wanted to reverse the order of my push/pop so that the number greater then 9 is the one that gets popped but I'll figure that one out. Please let me know if you have any ideas because I am not receiving any error messages when I compile which would tell me what's wrong with the program.

The reason you aren't getting any error messages is that all the code you have written is legal. When your code is legal and there is no run time error, then you need to start thinking about logic errors.

The above snippet means that if user enters a value > 9 the while loop will end, and the value of newnum will be ignored, not pushed on to stack. If you want to allow all values to be entered on to stack and then remove any value user has entered that is larger than 9, that's a different series of steps. Your code prevents the need to remove anything greater than 9, because those values aren't pushed in the first place.

In your Peek function you only allow peeking at the top value of the stack. You don't ask to look lower down. To do so would require additional code, and I think it would violate the spirit of using a stack to begin with, but it can be done. To look further down you would need to pop the top and store it in another, temporary stack. That way you can keep track of all the values peeked at. When you are done peeking you can pop the values off the temporary stack and push them back on the original stack. As you are peeking, if you don't like a value you can remove it from the original stack by not pushing it on the temporary stack. The problem is I think of peeking as looking and replacing, but not removing. If you remove, you intervene, not just peek.