Cod sursa(job #434337)

Utilizator alexandru92alexandru alexandru92 Data 5 aprilie 2010 17:39:34
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
/* 
 * File:   main.cpp
 * Author: SpeeDemon
 *
 * Created on April 5, 2010, 5:19 PM
 */
#include <string>
#include <cassert>
#include <fstream>
#define ERROR_SIGNAL -1000000000

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