Cod sursa(job #614827)

Utilizator BitOneSAlexandru BitOne Data 7 octombrie 2011 19:16:12
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <string>
#include <fstream>
#include <cstdlib>
#define LevMax 2
#define ERROR (-1<<29)

using namespace std;
string expresion;
string::const_iterator it, iend;
const string op[]={ "+-", "*/", "^" };
inline int eval( char op, int a, int b )
{
	switch( op )
	{
		case '+' : return a+b;
		case '-' : return a-b;
		case '*' : return a*b;
		case '/' : return a/b;
		default : return ERROR;
	}
}
int eval( int level )
{
	int x=0;
	if( level == LevMax )
	{
		if( '(' == *it )
		{
			++it;
			x=eval(0);
			++it;
		}
		else if( *it >= '0' && *it <= '9' )
				for( x=0; it < iend && *it >= '0' && *it <= '9'; ++it )
					x=x*10+*it-'0';
	}
	else for( x=eval(level+1); it < iend && string::npos != op[level].find(*it); )
		 {
			 char op=*it;
			 ++it;
			 x=eval( op, x, eval(level+1) );
		 }
	return x;
}
int main( void )
{
	ifstream in( "evaluare.in" );
	getline( in, expresion );
	it=expresion.begin();
	iend=expresion.end();
	ofstream out( "evaluare.out" );
	out<<eval(0)<<'\n';
	return EXIT_SUCCESS;
}