Cod sursa(job #272473)

Utilizator PopaStefanPopa Stefan PopaStefan Data 7 martie 2009 10:05:42
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include<fstream.h>
#include<string.h>
#include<stdlib.h>

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

void termen(char &b);
void factor(char &c);

char exp[100001];
int poz=0;
long long int stiva[100001];

char citire()
{char q;
fin.get(q);
if(q!='\n');
return q;
}

void expresie(char &a)
{char op;
termen(a);
while(a=='+' || a=='-')
   {op=a;
   a=citire();
   termen(a);
   exp[poz]=op;
   poz++;
   }
}

void termen(char &b)
{char op;
factor(b);
while(b=='*' || b=='/')
   {op=b;
   b=citire();
   factor(b);
   exp[poz]=op;
   poz++;
   }
}

void factor(char &c)
{if(c>='a' && c<='z' || c>='0' && c<='9')
  {exp[poz]=c;
  poz++;
  c=citire();
  while(c>='0' && c<='9')
     {exp[poz]=c;
     c=citire();poz++;
     }
  if(c=='+' || c=='-' || c=='*' || c=='/')
	  if(exp[poz-1]>='0' && exp[poz-1]<='9') {exp[poz]=',';poz++;}
  }
 else if(c=='(')
	{c=citire();
	expresie(c);
	c=citire();
	}

}

void calculare()
{int i=0,j,q,nr,semn=0,m=0;
char numar[8];
for(j=0;j<strlen(exp);j++)
   if(exp[j]>='0' && exp[j]<='9')
		   {nr=0;
		   for(q=j;exp[q]>='0' && exp[q]<='9';q++,nr++)
		       numar[nr]=exp[q];
		   numar[nr]='\0';
		   stiva[i]=atol(numar);
		   i++;j=q-1;
		   m++;
		   }
      else
	   if(exp[j]=='+') {stiva[i-2]=stiva[i-2]+stiva[i-1];
			 i--;semn++;
			 }
	   else  if(exp[j]=='-') //if(semn==m-2)
				      { stiva[i-1]=stiva[i-1]*(-1);
				  //else {stiva[i-2]=stiva[i-2]-stiva[i-1];
				      semn++;}

		    else if(exp[j]=='*')
				  {stiva[i-2]=stiva[i-2]*stiva[i-1];
				  i--;semn++;
				  }
			   else if(exp[j]=='/')
				 {stiva[i-2]=stiva[i-2]/stiva[i-1];
				  i--;semn++;
				  }
fout<<stiva[0];
}

int main()
{char c=citire();
expresie(c);
exp[poz]='\0';
calculare();
fin.close();
fout.close();
return 0;
}