I have a simple problem. The code doesn't run correctly and crashing. The problem is in main(); in second loop. While it tries to pop out the infos, it crashes.
Can anyone figure it out and help me? Here is my code.
Thanks in advance..
My question is, why does your pop function accept a book_info argument, and what are you trying to do with it?
Since it's a stack, the pop function should just pop the top element off -- you shouldn't have to pass that element to the function.
stack myStack; // Assume integers instead of book_infos, for simplicity
for (int i = 0; i < 4; ++i)
myStack.push(i);
// myStack now contains: 0 1 2 3 4
myStack.pop(2); // ???
?
pop should just remove the top element (and possibly return it, if you please). You shouldn't need to pass an argument for that.
Consider the pop member function of the standard std::stack container, for example:
void pop();
Remove top element
Removes the element on top of the stack, effectively reducing its size by one.
The element removed is the latest element inserted into the stack, whose value can be retrieved by calling member stack::top.
Your pop() returns the top element of the stack. I understood this. :)
But, what if I push two values, and then wanna pop those from top to bottom? i.e., from last inserted element to first inserted element into the stack?
pop should remove the top element from the stack.
When that happens, the second-to-top element becomes the new top element, so that will get popped if you call pop a second time.
That aside, here's just a few other comments:
-- Line 80 (st[top]=x;) goes out of bounds when the stack is full. In fact, you don't need it since the only thing you really need to do to pop the stack is to decrement top (which you do correctly in the next line). So, you can just remove line 80. If you do that, then you also won't need your book_info &x parameter.
-- You declare input_info as a member function of stack on line 28, even though you don't define it as such (and it doesn't need to be a member function). I would just remove that line.
-- As far as the actual definition of input_info, you don't actually need to pass a parameter to it. If you just add book_info book; at the first line of the input_info function, it'll be fine. In that case, you also won't need your n variable in main().
-- I would actually move the cin.ignore(); from line 100 to after line 53. That way, you don't have to call it yourself every time.