please use the code in the description and follow my directions exactly do this
ID: 3920430 • Letter: P
Question
please use the code in the description and follow my directions exactly do this in C++. USE MY CODE THAT I HAVE PLEASE AND JUST ADD THE NEW CODE!!!
Write a function postFixEval for stack-based evaluation of postfix expressions. The program reads postfix expressions and prints their values. Each input expression should be entered on its own line, and the program should terminate when the user enters a blank line. Assume that there are only binary operators and that the expressions contain no variables. Your program should use a tack. Here are sample input-output pairs.
78 78
78 6 + 84
78 6 + 9 2 - / 12
Explanation / Answer
#include<iostream>
#include<stack>
#include<string>
using namespace std;
//method to evaluate postfix exp using stack
int postFixEval (string exp);
//method to perform operation
int Operation(char operation, int operand1, int operand2);
bool IsOperator(char C);
bool isNumeric(char C);
int main()
{
string exp;
int i=0;
while(1)
{
//stops when user enter blank line...
cout<<" Enter Postfix exp ";
getline(cin,exp);
i=0;
while(exp[i]!='')i++;
if(i==0)break;//if blank line entered then stoping program
int result = postFixEval (exp);
cout<<"Output = "<<result<<" ";
}
}
int postFixEval (string exp)
{
//creating stakc
stack<int> S;
for(int i = 0;i< exp.length();i++) {
//excluding space
if(exp[i] == ' ' || exp[i] == ',') continue;
//if it is operator then
else if(IsOperator(exp[i])) {
// Pop two values.
int operand2 = S.top(); S.pop();
int operand1 = S.top(); S.pop();
// ///perform operation
int result = Operation(exp[i], operand1, operand2);
//push result to stack
S.push(result);
}
else if(isNumeric(exp[i])){
//if numeric..
int operand = 0;
//making a number...upto space
while(i<exp.length() && isNumeric(exp[i])) {
operand = (operand*10) + (exp[i] - '0');
i++;
}
i--;
//push value to stack
S.push(operand);
}
}
return S.top();
}
bool isNumeric(char C)
{
if(C >= '0' && C <= '9') return true;
return false;
}
bool IsOperator(char C)
{
if(C == '+' || C == '-' || C == '*' || C == '/')
return true;
return false;
}
int Operation(char operation, int operand1, int operand2)
{
if(operation == '+') return operand1 +operand2;
else if(operation == '-') return operand1 - operand2;
else if(operation == '*') return operand1 * operand2;
else if(operation == '/') return operand1 / operand2;
else cout<<"Unexpected Error ";
return -1;
}
output:
Enter Postfix exp
1 2 +
Output = 3
Enter Postfix exp
2 5 + 6 *
Output = 42
Enter Postfix exp
1 11 * 2 -
Output = 9
Enter Postfix exp
Process exited normally.
Press any key to continue . . .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.