Cod sursa(job #837143)

Utilizator simplicityFlorescu Emanuel Robert simplicity Data 17 decembrie 2012 15:57:18
Problema Evaluarea unei expresii Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include<fstream>
#include<stack>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char e[100004],opcrt;
stack<char>op;
stack<int>v;
int n,a,b,i;
void operatie(){
	a=v.top();
	v.pop();
	b=v.top();
	v.pop();
	opcrt=op.top();
	op.pop();
	switch(opcrt)
	{
	case '+':{v.push(a+b);break;}
	case '-':{v.push(b-a);break;}
	case '*':{v.push(a*b);break;}
	case '/':{v.push(b/a);break;}
	}
	
}
int numar(){
	int x=i;
	int nr=0;
		while('0'<=e[x] && e[x]<='9')
		{
			nr=nr*10+e[x++]-'0';
		}
		i=x-1;
		return nr;
}
int main(){
	f>>e;
	i=0;
	while(e[i]!='\0')
	{
		switch(e[i])
		{
		case '(':{
			op.push(e[i]);
			break;}
		case ')':
			while(op.top()!='(')
			{
				operatie();
			}
			op.pop();break;
		case '+':case '-':{
			while(!op.empty() && op.top()!='(')
			{
				operatie();
			}	
			op.push(e[i]);break;
		}
		case'*':case'/':
			{	if(!op.empty()){
				
				if(op.top()=='/'){
					a=v.top();v.pop();b=v.top();v.pop();
				v.push(b/a);break;}
				else if(op.top()=='*'){
					a=v.top();v.pop();b=v.top();v.pop();
				v.push(b*a);break;}
			}
				op.push(e[i]);
				break;
			}
	default:{
		a=numar();
		v.push(a);
		}
		}
	i++;
	}
		while(!op.empty())
		{
			operatie();
		};
	g<<v.top();
return 0;
}