We normally write arithmetical expressions using infix notation, meaning that th
ID: 3765519 • Letter: W
Question
We normally write arithmetical expressions using infix notation, meaning that the operator appears between its two operands, as in "4 + 5". In postfix notation, the operator appears after its operands, as in "4.3 5.0 +". Here is a slightly more complex postfix expression: "25 12 7 - 2 * /". The equivalent infix expression is: "25 / ((12 - 7) * 2)". The result of that expression should be 2.5 (beware integer division). Postfix expressions don't require parentheses.
Write a function named postfixEval that uses a stack (from the Standard Template Library) to evaluate postfix expressions. It should take a C-style string parameter that represents a postfix expression. The only symbols in the string will be +, -, *, /, digits and spaces. '+' and '-' will only appear in the expression string as binary operators - not as unary operators that indicate the sign of a number. The return type should be double. You may find the isdigit() function useful in parsing the expression. You may also use strtok() and atof(). Hint: Read a postfix expression from left to right. When you read a number, push it on the stack. When you read an operand, pop the top two numbers off the stack, apply the operator to them, and push the result on top of the stack. At the end, the result of the expression should be the only number on the stack.
File must be called: postfixEval.cpp
Explanation / Answer
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string.h>
using namespace std;
bool isOperator(char oper)
{
if (oper=='+' || oper=='-' || oper=='*' || oper=='/')
return true;
else
return false;
}
double process(double op1, double op2, char oper)
{
double result;
switch(oper){
case '+':
result = op2 + op1;
break;
case '-':
result = op2 - op1;
break;
case '*':
result = op2 * op1;
break;
case '/':
result = op2 / op1;
break;
}
//cout << op1 << " " <<op2 << " " <<oper << "= " << result <<endl;
return result;
}
int main()
{
char expr[1000], buffer[15];
int i, len, j;
double op1, op2, temp;
stack<double> s;
cout << ("Enter a Postfix Expression: ") <<endl;
gets(expr);
len = strlen(expr);
j = 0;
for(i=0; i<len;i++){
if(expr[i]>='0' && expr[i]<='9'){
buffer[j++] = expr[i];
}
else if(expr[i]==' '){
if(j>0){
buffer[j] = '';
temp = atof(buffer);
s.push(temp);
j = 0;
}
}
else if(isOperator(expr[i])){
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
temp = process(op1, op2, expr[i]);
s.push(temp);
}
}
cout << temp <<endl;
cout << "Expr: "<<expr<<" Result= "<< s.top() <<endl;
return 0;
}
--------output---------------
Enter a Postfix Expression:
25 12 7 - 2 * /
2.5
Expr: 25 12 7 - 2 * / Result= 2.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.