Cod sursa(job #672323)

Utilizator BitOneSAlexandru BitOne Data 1 februarie 2012 21:03:11
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <string>
#include <fstream>
#include <cstdlib>
#define ERROR 1<<30

using namespace std;

string exp;
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;
		default  : return ERROR;		
	}
}
inline int eval( int level )
{
	int x;
	if( 2 == level )
	{
		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 return ERROR;
	}
	else for( x=eval(level+1); it < iend && string::npos != op[level].find(*it) ; )
		 {
			 char op=*it;
			 ++it;
			 x=eval( x, eval(level+1), op );
		 }	
	return x;
}
int main()
{
	ifstream in( "evaluare.in" );
	
	getline( in, exp );
	it=exp.begin(), iend=exp.end();
	
	ofstream out( "evaluare.out" );
	out<<eval(0)<<'\n';
	
	return EXIT_SUCCESS;
}