I am trying to make a function that can evaluate a postfix expression, returning the string "invalid" if it is not valid or complete. This is the code I have, but it is not working and I cannot figure out why...is there a better way?
string ExpressionManager::postfixEvaluate(string postfixExpression)
{
stack<int> num;
stringstream ss;
ss << postfixExpression;
string eval;
while(ss >> eval)
{
if(isNum(eval) == true)
{
int digit;
stringstream convert(eval);
convert >> digit;
num.push(digit);
}
if(OPERATORS.find(eval) == true && num.size() >= OPER_PAIR)
{
if(eval == "+")
{
int right = num.top();
num.pop();
int left = num.top();
num.pop();
num.push(left + right);
}
if(eval == "-")
{
int right = num.top();
num.pop();
int left = num.top();
num.pop();
num.push(left - right);
}
if(eval == "*")
{
int right = num.top();
num.pop();
int left = num.top();
num.pop();
num.push(left * right);
}
if(eval == "/")
{
int right = num.top();
num.pop();
int left = num.top();
if(left == EMPTY) //Checks for 0 to avoid dividing by zero
{
return "invalid";
}
num.pop();
num.push(left / right);
}
if(eval == "%")
{
int right = num.top();
num.pop();
int left = num.top();
if(left == EMPTY)
{
return "invalid";
}
num.pop();
num.push(left % right);
}
}
else
{
return "invalid";
}
}
if(num.size() > 1)
{
return "invalid";
}
else
{
string expression;
stringstream ex;
ex << num.top();
expression = ex.str();
return expression;
}
}