I\'m trying to create a program that converts an arithmetic expression from infix to postfix form. As long as I don\'t call the \"infixToPostFix\" function, the program runs
I ran into this problem too. I think the problem is in this sort of code:
else if (token.getType() == CLOSE)
{
token = stack.top();
stack.pop();
while (token.getType() != OPEN)
{
postfix.push_back(token);
token = stack.top();
stack.pop();
}
}
The problem is that 'token' is a reference to the top, not a copy. So you can't pop the stack until you are done working with token. In my case, it often still worked because the information was still present, but then it would crash at weird times. You need to organize this code in a different way to pop only after you done working with 'token'.
Maybe something like:
else if (token.getType() == CLOSE)
{
token = stack.top();
Token saveToken = new Token(token); // Or something like this...
stack.pop();
while (saveToken.getType() != OPEN)
{
postfix.push_back(saveToken);
token = stack.top();
delete saveToken; // ugh
Token saveToken = new Token(token);
stack.pop();
}
delete saveToken; //ugh
}
You are calling top on empty stack, just follow the code for your test.
stack
is implemented using container
, since stack
is container adaptor
, by default deque
is used. In probably one line of your code - you call pop/top
on empty stack
, that is not allowed.
trace
show, that error is after Token +
.
Problem is here:
else if (token.getType() == OPERATOR)
{
Token topToken = stack.top();
You try to top
from empty stack
, since stack
in case, where is only NUMBER
token before OPERATOR
token, is empty.