Reputation: 1
My code suppose to calculate the values of postfix expression. But I am stuck at "result" which i dont know how to write the code. I wrote : result = operand1 operation.push operand2 and logically will give an error. I used 2 stack.
int main()
{
string input;
cout << "Enter a postfix expression: " << endl;
getline(cin, input);
double operand1, operand2, result;
stack<double> number;
stack<char>operation;
int i=0;
while (i < input.length())
{
if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/' || input[i] == '^')
operation.push(input[i]);
else
number.push(input[i]);
i++;
}
operand2 = number.top( );
number.pop( );
operand1 = number.top( );
number.pop( );
result = operand1 operation.push(input[i]) operand2
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return 0;
}
Can anyone suggest a better solution? Thank you
Upvotes: 0
Views: 1372
Reputation: 36082
first of all you only need one stack
then the expression
result = operand1 operation.push operand2
doesn't look like any postfix I know, instead I was expecting something like
operand1 operand2 operator
so you push operands on the stack and whenever you find a operator, you pop the two topmost items on the stack and push the result.
e.g.
infix 10 * ( 12 + 15 ) -> postfix 12 15 + 10 *
then when evaluating it (pseudo code)
push -> 12 [operand]
push -> 15 [operand]
pop -> + [operator]
push result 12+15 [operand]
push 10 [operand]
pop -> * [operator]
push result 27*10 [operand]
Upvotes: 0
Reputation: 16226
You need to make a switch
on the operator and compute the result yourself:
char op = operation.top();
switch( op ) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': result = operand1 / operand2; break;
case '^': result = pow(operand1, operand2) ; break;
}
Upvotes: 1