Cod sursa(job #3254148)

Utilizator vladorovOroviceanu Vlad vladorov Data 6 noiembrie 2024 12:06:05
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int expresie();
int termen();
int factor();
int constanta();

int index=0;
string expr;

int expresie(){
    int t=termen();

    while(expr[index]=='+' || expr[index]=='-'){
        if(expr[index]=='+'){
            index++;
            t+=termen();
        }else{
            index++;
            t-=termen();
        }
    }

    return t;
}

int termen(){
    int f=factor();

    while(expr[index]=='*' || expr[index]=='/'){
        if(expr[index]=='*'){
            index++;
            f*=factor();
        }else{
            index++;
            f/=factor();
        }
    }

    return f;
}

int factor(){
    int f;

    if(expr[index]=='('){
        index++;
        f=expresie();
        index++;
    }else{
        f=constanta();
    }

    return f;
}

int constanta(){
    string c;

    while('0'<=expr[index] && expr[index]<='9'){
        c+=expr[index];
        index++;
    }

    return stoi(c);
}

int main(){
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");

    fin>>expr;

    fout<<expresie();

    return 0;
}