Cod sursa(job #155955)

Utilizator MciprianMMciprianM MciprianM Data 12 martie 2008 11:45:07
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include<fstream>
#include<string.h>
using namespace std;
char e[1001] ;
int l;
char  st[1001];
long pf[1001];
int pfl, stl;
int prior(char op){
  switch(op){
    case '+':;
    case '-':return 1;
    case '/':;
    case '*':return 2;
    case '(':return 0;
    case '#':return -1;
    default: return -1;
  }
}

long val(long a, long b, char op){
  switch(op){
    case '+': return a+b;
    case '-': return a-b;
    case '*': return a*b;
    case '/': return a/b;
    default : return -1;
  }
}
void calc(){
  long a, b;
  a=pf[pfl-1];
  pfl--;
  b=pf[pfl-1];
  pfl--;
  long r=val(b,a,st[stl-1]);
  pf[pfl++]=r;
}
void eval(){
  int i;
  long r;
  for(i=0;i<l;i++){
     r=0;
     if(e[i]=='(')
       st[stl++]=e[i];
     else
       if(strchr("0123456789",e[i])){
	 while((strchr("0123456789",e[i]))&&i<l){
	   r=r*10+(e[i]-'0');
	   i++;
	 }
	 pf[pfl++]=r;
	 i--;
       }
       else
	if(strchr("+-*/",e[i])){
	  while(prior(e[i])<=prior(st[stl-1])){
	    calc();
	    stl--;
	  }
	  st[stl++]=e[i];
	}
	else
	  if(e[i]==')'){
	    while(st[stl-1]!='('){
	      calc();
	      stl--;
	    }
	    stl--;
	  }
  }
  while(stl-1>0){
    calc();
    stl--;
  }
}
int main(){
   ifstream f("expresie.in");
   f>>e;
   f.close();
   l=strlen(e);
   st[stl++]='#';
   eval();
   ofstream g("expresie.out");
   g<<pf[pfl-1]<<'\n';
   g.close();
   return 0;
}