Cod sursa(job #361458)

Utilizator PopaStefanPopa Stefan PopaStefan Data 5 noiembrie 2009 10:35:05
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include<fstream>
#include<string.h>
#include<stdlib.h>

using namespace std;

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

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

char exp[1000001];
int poz=0;
long long int stiva[1001];

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,p,q,nr,semn;
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]=atoll(numar);
		   i++;j=q-1;
		   }
      else
	   if(exp[j]=='+') {stiva[i-2]=stiva[i-2]+stiva[i-1];
			 i--;
			 }
	   else  if(exp[j]=='-')  {stiva[i-2]=stiva[i-2]-stiva[i-1];
				  i--;
				  }
		    else if(exp[j]=='*')
				  {stiva[i-2]=stiva[i-2]*stiva[i-1];
				  i--;
				  }
			   else if(exp[j]=='/')
				 {stiva[i-2]=stiva[i-2]/stiva[i-1];
				  i--;
				  }
fout<<stiva[0];
}

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