Cod sursa(job #504813)

Utilizator BitOneSAlexandru BitOne Data 28 noiembrie 2010 20:06:04
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <string>
#include <cstdlib>
#include <fstream>

using namespace std;

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