点击查看代码
//Evaluation Of postfix Expression using stack
#include<iostream>
#include<stack>//stack from standard template library(STL)
#include<string>
using namespace std;
int EvaluatePostfix(string exp);
bool IsOperator(char c);
int PerformOperation(char operation, int op1, int op2);
bool IsNumericDigit(char c);
int main() {
string expression;
getline(cin, expression);//与cin>>不同,可以读取空格,直到整行换行符结束
int result = EvaluatePostfix(expression);
cout << "Output = " << result << "\n";
}
int EvaluatePostfix(string exp) {
stack<int> S;//存放操作数及运算结果
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == ' '||exp[i]==',') continue;//设置操作数之间分隔符
else if (IsOperator(exp[i])) {//拿出最后两个操作数进行运算
int op2 = S.top();//类型转换
S.pop();
int op1 = S.top();
S.pop();
int result = PerformOperation(exp[i], op1, op2);
S.push(result);//运算结果放回
}
else if (IsNumericDigit(exp[i])) {//一位一位的读取操作数
int operand = 0;//初始化为0
while (i < exp.length() && IsNumericDigit(exp[i])) {
operand = operand * 10 + (exp[i] - '0');//右移进位
//使用exp[i]-'0'将ASCII值转化成目标整数
i++;
}
i--;//退回到已读最后一位
S.push(operand);//放入完整操作数
}
}
return S.top();//最终结果
}
bool IsOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/')
return true;
return false;
}
int PerformOperation(char operation, int op1, int op2) {
if (operation == '+') return op1 + op2;
else if (operation == '-') return op1 - op2;
else if (operation == '*') return op1 * op2;
else if (operation == '/') return op1 / op2;
else cout << "Unexpected Error \n";
return -1;
}
bool IsNumericDigit(char c) {
if (c >= '0' && c <= '9') return true;
return false;
}