I don't know what's going wrong with this. Here's the code that I think is messing it up: the main evaluation process, of course.
postfix: 8 4 + = 8 + 4
Code:
int evaluatePostfixExpression(char postfix[])
{
int i, length;
int x,y;
STACK stack;
initStack(&stack); // initializze stack
get_postfix(postfix); // get postfix expression from user
length = strlen(postfix);
// if strlen if postfix is more than zero
if ( length )
{
for ( i=0; i<length; i++ )
{
/* if current operator in postfix is a digit */
if ( isdigit(postfix[i]) )
{
push(&stack, postfix[i]);
}
/* if current operator in postfix is an operator */
else if ( isOperator(postfix[i]) )
{
x = pop(&stack);
y = pop(&stack);
push(&stack, calculate(y, x, postfix[i]) );
}
}
return(pop(&stack));
}
else
return -1;
}
subtraction and mod seem to be working. Addition, multiplication and division are returning answers where 0=96, 1=97 etc. The exponent might as well be a random number generator :P
Calculate and isOperator functions just in case:
Code:
int calculate(int op1, int op2, char the_operator)
{
if(the_operator == '+')
return(op1 + op2);
else if(the_operator == '-')
return(op1 - op2);
else if(the_operator == '*')
return(op1 * op2);
else if(the_operator == '/')
return(op1 / op2);
else if(the_operator == '^')
return(op1 ^ op2);
else if(the_operator == '%')
return(op1 % op2);
}
int isOperator(char c) // is c and operator
{
if ( c == '+' || c == '-' || c == '*' ||
c == '/' || c == '%' || c == '^' )
{
return TRUE;
}
else
return FALSE;
}
edit: http://k5-k.element80.net/files/saa1213.cpp for the entire file.
more edit: It was taking the ascii values. So if I subtract 48 from each op1 and op2 it fixes the strange output problems with simple input. Of course, then I had to add 48 when calling the calculate function so I can switch between working with ascii values and integers. So it's almost working. One more thing to fix. Don't worry about it. Might be useful later on for people who use the search, as there was lots on infix to postfix, but not much on postfix.