Through doing a little research online, I've found that this is error is caused by trying to pop something off an empty stack. In my code, I thought I tried to make sure this exact thing wouldn't happen by storing the top of my stack in a temporary string called c
, but for some reason the error keeps occurring. This is a project related to converting infix notation to postfix notation. When I input 1+2+3
, I should get 12+3+
, but instead this error occurs. The error occurs in the precedence while loop.
stack <string> InfixToPostfix(char * expr)
{
// YOUR CODE STARTS HERE!
char* token;
stack<string> s;
string postfix;
stack<string> p;
// use stack s to manipulate the infix to postfix
s.push("(");
token = strtok (expr," "); // get the first token
while(!s.empty())
{
if(token=="(")
{
s.push(token);
}
else if(token==")")
{
string c=s.top();
s.pop();
while(c != "(")
{
postfix += c + " ";
c = s.top();
s.pop();
}
}
else if(isNumber(token))
{
postfix+=token;
}
else
{
while(precedence(s.top())>=precedence(token))
{
//put on bottom if need be
string c = s.top();
s.pop();
postfix += c;
postfix += " ";
}
s.push(token);
}
token = strtok(NULL, " "); // use blanks as delimiter
if (token == NULL) // no more tokens, exit the loop
break;
}
p.push(postfix);
return p;
}