Evaluating a Postfix expression

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;
}
}
Hi!

Try re-editing your post to encase the code block in [code] tags.

This should make it more legible for us :)

Joe
Last edited on
What input makes it fail?
Can you supply some input and output - valid and invalid ?

EDIT

Just found this post on stackoverflow.com It seems quite easy to validate a postfix expression.
http://stackoverflow.com/questions/789847/postfix-notation-validation
Last edited on
Topic archived. No new replies allowed.