//思想:从文件中读入不含括号的算术表达式,再输出到另一个文件
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stack>
using namespace std;
#define N 100
int judge(char c,int a,int b){//根据运算符和运算数定义运算数
switch(c){
case '+':return a+b;break;
case '-':return a-b;break;
case '*':return a*b;break;
case '/':return a/b;break;
default:
return 0;
break;
}
}
int main(){
stack<int> t1;//操作数栈
stack<char> t2;//运算符栈
t2.push('#');
FILE *fp1,*fp2;
char s[N];
fp1=fopen("5.in","r");
fp2=fopen("5.out","w");
fscanf(fp1,"%s",s);
int len=strlen(s);
for(int i=0;i<len;i++){
if(s[i]>='0'&&s[i]<='9'){
int sum=s[i]-'0';
while(s[i+1]>='0'&&s[i+1]<='9'){
sum=sum*10+(s[i+1]-'0');
i++;
}
t1.push(sum);
}
else if(s[i]=='+'||s[i]=='-'){//如果已经是加号或者减号,则已经是最低等级了
if(t2.top()=='#')t2.push(s[i]);//符号栈为空则直接压进否则弹出
else{//否则一直弹出符号元素直至栈底
while(t2.top()!='#'){
int temp1=t1.top();t1.pop();
int temp2=t1.top();t1.pop();
int temp3=judge(t2.top(),temp2,temp1);
t1.push(temp3);
t2.pop();
}
t2.push(s[i]);//弹出完后再压进栈
}
}
else {
if(t2.top()=='#'||t2.top()=='+'||t2.top()=='-')t2.push(s[i]);
else{
while(t2.top()=='*'||t2.top()=='/'){
int temp1=t1.top();t1.pop();
int temp2=t1.top();t1.pop();
int temp3=judge(t2.top(),temp2,temp1);
t1.push(temp3);
t2.pop();
}
t2.push(s[i]);
}
}
}
while(t2.top()!='#'){//当符号栈顶不为空时继续弹出元素
int temp1=t1.top();t1.pop();
int temp2=t1.top();t1.pop();
int temp3=judge(t2.top(),temp2,temp1);
t1.push(temp3);
t2.pop();
}
fprintf(fp2,"%d",t1.top());
return 0;
}