// test20.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class PostExp{
public:
PostExp(string str):evalStr(str){}
int evaluate();
private:
string evalStr;
stack<int> postStack;
};
/**
算式中的數字限定在0~9,因為是通過string分別讀取每一個元素,如89被認定為8和9
如果操作數要擴大到9以上,則應該用數組保存算式中的每一個元素
此處為方便起見,只是為了表達后綴表達式的基本算法
*/
int PostExp::evaluate(){//后綴表達式計算
for(string::iterator iter=evalStr.begin(); iter!=evalStr.end(); iter++){//從前至后讀取
int x,y,z;
if(*iter>='0' && *iter<='9')
postStack.push(*iter - '0');//如果讀到數字,壓棧
else{//如果讀到操作符,出棧兩個操作數,并計算
y=postStack.top();//y保存操作符右邊的數字
postStack.pop();
x=postStack.top();//x保存操作符左邊的數字
postStack.pop();
switch(*iter){
case '+': z=x+y; break;//z保存計算結果
case '-' : z=x- y; break;
case '*': z=x*y; break;
case '/' : z=x/y; break;
}
postStack.push(z);//把計算結果作為操作數壓棧
}
}
return postStack.top();
}
int main(){
PostExp* pe=new PostExp("352*5+-");
cout<<pe->evaluate();
system("pause");
}