Pagini recente » Cod sursa (job #186972) | Cod sursa (job #360766) | Cod sursa (job #182884) | Cod sursa (job #2580040) | Cod sursa (job #2228845)
#include<fstream>
#include<iostream>
#include<string.h>
#include<stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char postf[100005], inf[100005];
int n, m;
char w,aux;
stack<char>stivcik;
int imp(char s){
if(s=='(') return 0;
if(s == '+' || s=='-') return 1;
return 2;
}
long evaluare(){
stack<int> stiva;
long num;
int i = 0;
while(i<n){
while(postf[i]==' ' || postf[i]=='\t') ++i;
if(postf[i]>47 && postf[i]<58){
num = 0;
while(i<n && postf[i]>47 && postf[i]<58){
num*=10;
num+=(postf[i]-48);
++i;
}
stiva.push(num);
}
if(postf[i]=='+'){
long op1 = stiva.top();
stiva.pop();
long op2 = stiva.top();
stiva.pop();
stiva.push(op1+op2);
i++;
}
if(postf[i]=='*'){
long op1 = stiva.top();
stiva.pop();
long op2 = stiva.top();
stiva.pop();
stiva.push(op1*op2);
i++;
}
if(postf[i]=='-'){
long op1 = stiva.top();
stiva.pop();
long op2 = stiva.top();
stiva.pop();
stiva.push(op2-op1);
i++;
}
if(postf[i]=='/'){
long op1 = stiva.top();
stiva.pop();
long op2 = stiva.top();
stiva.pop();
stiva.push(op2/op1);
i++;
}
}
return stiva.top();
}
void conversie(){
int i = 0;
n = 0;
while(i<m){
w = inf[i];
if(w>47 && w<58){
postf[n++] = inf[i];
if(inf[i+1]<48 || inf[i+1]>57){ postf[n++] = ' ';}
}
else if( w == '('){
stivcik.push(w);
}
else if(w==')'){
aux = stivcik.top();
while(aux!='('){
postf[n++] = aux;
postf[n++] = ' ';
stivcik.pop();
aux = stivcik.top();
}
stivcik.pop();
}
else{
if(stivcik.empty()){ stivcik.push(w);
}
else{
while(!stivcik.empty() && imp(stivcik.top())>imp(w)){
postf[n++] = stivcik.top();
postf[n++] = ' ';
stivcik.pop();
}
stivcik.push(w);
}
}
i++;
}
while(!stivcik.empty()){
postf[n++] = stivcik.top();
postf[n++] = ' ';
stivcik.pop();
}
}
int main ()
{
fin>>inf;
m = strlen(inf);
conversie();
fout<<'\n'<<evaluare();
return 0;
}