In: Computer Science
Postfix Arithmetic Operation (C++) Friday, 27 September 2019, 04:21 PM Use stack to implement postfix arithmetic operation. Input Many test cases until EOF. Each line is a postfix arithmetic operation formula. There is no blank between the numbers, and the number only is 0-9. Output The result of each line. But if the postfix arithmetic operation formula is wrong (it means you can't get the correct answer), please output "Input Error". Sample Input 35+ 3+5 63/14-*3+8- Sample Output 8 Input Error -11.
postfixEval.cpp
#include<iostream>
#include<fstream>
#include<stack>
using namespace std;
string evaluateExpr(string expr)
{
//create stack using STL
stack<double> st;
for(int i=0;i<expr.length();i++)
{
//If we got operand then push onto
stack
if(expr[i]>='0' &&
expr[i]<='9')
{
//expr[i]-'0' to
convert character to integer
st.push(expr[i]-'0');
}
//If we get operator
else
{
//pop 2 elements
from stack
double
left,right;
//If stack is
empty i.e. Error
if(st.empty())
{
return "Input Error";
}
else
{
//First popping element will be the right
operand
right=st.top();
st.pop();
}
//If stack is
empty i.e. Error
if(st.empty())
{
return "Input Error";
}
else
{
//second popping element will be the left
operand
left=st.top();
st.pop();
}
//do the
operations accordingly and push the result to stack
if(expr[i]=='+')
{
st.push(left+right);
}
else
if(expr[i]=='-')
{
st.push(left-right);
}
else
if(expr[i]=='*')
{
st.push(left*right);
}
else
if(expr[i]=='/')
{
st.push(left/right);
}
//If we got
character other than +, -, *, / the return error
else
{
return "Input Error";
}
}
}
//return the top of the stack by converting int to
string
return to_string(st.top());
}
int main()
{
//Open file
ifstream file;
file.open("input.txt");
string expr;
//iterate until we found EOF
while(getline(file,expr))
{
//Function calling and printing the
output
cout<<evaluateExpr(expr)<<endl;
}
//Closing file
file.close();
return 0;
}
output screenshot:
input.txt
35+
3+5
63/14-*3+8-