Cod sursa(job #494773)

Utilizator BitOneSAlexandru BitOne Data 22 octombrie 2010 21:30:14
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

/*
 *
 */
using namespace std;
string expresion;
string::iterator it, iend;
const string op[3]={ "+-", "*/", "^" };
inline int eval( int a, int b, char op )
{
	switch( op )
	{
		case '+' : return a+b;
		case '-' : return a-b;
		case '*' : return a*b;
		case '/' : return a/b;
	}
	return 0;
}
inline int eval( int lev )
{
	int x;
	char o;
	if( lev == 2 )
	{
		if( '(' == *it )
		{
			++it;
			x=eval(0);
			++it;
		}
		else for( x=0; it < iend && *it >= '0' && *it <= '9'; ++it )
				x=x*10+*it-'0';
	}
	else for( x=eval(lev+1); it < iend && string::npos != op[lev].find(*it); o=*it, ++it, x=eval( x, eval(lev+1), o )  );
	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;
}