Cod sursa(job #668029)

Utilizator psycho21rAbabab psycho21r Data 24 ianuarie 2012 10:08:25
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

string str;
int i=0;
vector < string > operands;

long compute(long a, long b, char c)
{
    switch (c)
    {
        case '+': return a+b;
        case '-': return a-b;
        case '*': return a*b;
        case '/': return a/b;
    }
}

bool op(long h, char c)
{
    if(h==0&&(c=='+'||c=='-'))
        return true;
    if(h==1&&(c=='*'||c=='/'))
        return true;
    if(h==2&&(c=='^'))
        return true;
    return false;

}

long evaluate(long);

long factor ()
{
    long r=0;
    if (str[i]=='(')
    {
         ++i;
         r=evaluate(0);
         ++i;
    }
    else
    {
        while(str[i]>='0'&&str[i]<='9')
            r = r*10 + str[++i-1] - '0';
    }
    return r;
}

long evaluate (long h)
{
    long r = (h==2)?factor():evaluate(h+1);
    while (op(h,str[i]))
    {
        r = compute(r, evaluate(h+1), str[++i-1]);
    }
    return r;
}

int main()
{
    ifstream in("evaluare.in");
    getline (in, str);
    in.close();
    ofstream out("evaluare.out");
    out << evaluate(0);
    out.close();

    return 0;
}