Cod sursa(job #1155030)

Utilizator Andrei1998Andrei Constantinescu Andrei1998 Data 26 martie 2014 16:30:19
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <cstring>

using namespace std;

char sir[100005];
int n,poz;

int termen();
int factor();

int eval()
{
    //cout<<"eval("<<poz<<")\n";
    int x=termen();
    while(sir[poz]=='+' || sir[poz]=='-')
    {
        if(sir[poz++]=='+')
        {
            x+=termen();
        }
        else
        {
            x-=termen();
        }
    }

    return x;
}

int termen()
{
    //cout<<"termen("<<poz<<")\n";
    int x=factor();

    while(sir[poz]=='*' || sir[poz]=='/')
    {
        if(sir[poz++]=='*')
        {
            x*=factor();
        }
        else
        {
            x/=factor();
        }
    }

    return x;
}

int factor()
{
    //cout<<"factor("<<poz<<")\n";
    if(sir[poz]=='(')
    {
        poz++;
        int x=eval();
        poz++;
        return x;
    }

    int x=0;
    while(sir[poz]>='0' && sir[poz]<='9')
    {
        //cout<<"yay"<<endl;
        x*=10;
        x+=(sir[poz++]-'0');
    }
    //cout<<"am intors "<<x<<endl;
    return x;
}

int main()
{
    ifstream cin("evaluare.in");
    ofstream cout("evaluare.out");

    cin.get(sir,100005);
    n=strlen(sir);
    cout<<eval()<<'\n';

    cin.close();
    cout.close();
    return 0;
}