Cod sursa(job #758081)

Utilizator Vladinho97Iordan Vlad Vladinho97 Data 14 iunie 2012 12:59:24
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include<fstream>
#include<math.h>
using namespace std;
int parseS(char*&exp);
int parseE(char*&exp);
enum Operator {
	Plus,
	Minus,
	Inmultit,
	Impartit,
	Deschisa,
	Inchisa,
	Eroare
};

bool esteOperatorAditiv(const char* exp) {
	if(exp[0]=='+')
		return 1;
	if(exp[0]=='-')
		return 1;
	return 0;
}

Operator operat(char* &exp) {
	if(exp[0]=='+')
	{	
		exp++;
		return Plus;}
	if(exp[0]=='-')
	{	
		exp++;
		return Minus;}
	if(exp[0]=='*')
	{	
		exp++;
		return Inmultit;}
	if(exp[0]=='/')
	{	exp++;
		return Impartit;}
	if(exp[0]=='(')
	{
		exp++;
		return Deschisa;}
	if(exp[0]==')')
	{
		exp++;
		return Inchisa;
	}
	return Eroare;
}

bool esteParantezaDeschisa(char* &exp){
	if(exp[0]=='(')
		return 1;
	return 0;
}
bool esteParantezaInchisa(char* &exp){
	if(exp[0]==')')
		return 1;
	return 0;
}
bool esteOperatorMultiplicativ(const char* exp) {
	if(exp[0]=='*')
		return 1;
	if(exp[0]=='/')
		return 1;
	return 0;
}

int parseN(char* &exp) {
	int i=0,aux=0;
	while(exp[i]-'0'>=0&&exp[i]-'0'<10)
	{
		aux*=10;
		aux+=exp[i]-'0';
		i++;
	}
	exp+=i;
	return aux;
}

int parseP(char* &exp){
	int p=0;
	p=parseE(exp);
	while (esteOperatorMultiplicativ(exp)) {
		Operator op = operat(exp);
		if(op==Inmultit)
			p*=parseE(exp);
		if(op==Impartit)
			p/=parseE(exp);
	}
	return p;
}

int parseE(char* &exp){
	int s;
	if (esteParantezaDeschisa(exp)) {
		exp++; // parse (
		s = parseS(exp);
		exp++; // parse )
	} else {
		s = parseN(exp);
	}
	return s;
}

int parseS(char* &exp) {
	int s;
	s = parseP(exp);
	while(esteOperatorAditiv(exp))
	{
		Operator op = operat(exp);
		if(op==Plus)
			s+=parseP(exp);
		if(op==Minus)
			s-=parseP(exp);
	}
	return s;
}


char a[100001];
int main()
{
	ifstream f("evaluare.in");
	ofstream g("evaluare.out");
	char *p = a;
	f >> a;
	int suma=parseS(p);
	g <<suma;
	return 0;
}