Cod sursa(job #2922628)

Utilizator CookieDaggerDragan Iulian CookieDagger Data 9 septembrie 2022 10:44:35
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <string>
#include <fstream>

using namespace std;

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

string operations = "+-*/";

string trimBraces(string s){
    if(s.length() < 5) return s;
    if((s[0]) == '(' && s[s.length() - 1] == ')'){
        return s.substr(1, s.length()-1);
    }
    return s;
}

int eval(string s) {
    int nested = 0;
    int currOp = 10, currOpIndex;   
    for(int i=0; i<s.length(); i++) {
        char c = s[i];
        if(c == '(') {
            nested++;
            continue;
        } else if(c == ')') {
            nested--;
            continue;
        }
        if(nested == 0){
            int found = operations.find(c);
            if(found != string::npos){
                if(found < currOp){ 
                    currOp = found;
                    currOpIndex = i;
                };
            }
        }
    }
    if(currOp == 10){
        return stoi(s);
    }
    string lhs = trimBraces(s.substr(0, currOpIndex));
    string rhs = trimBraces(s.substr(currOpIndex + 1, s.length()));
    if(currOp == 0){
        return eval(lhs) + eval(rhs);
    }   
    if(currOp == 1){
        return eval(lhs) - eval(rhs);
    }   
    if(currOp == 2){
        return eval(lhs) * eval(rhs);
    }   
    if(currOp == 3){
        return eval(lhs) / eval(rhs);
    }   
}

int main()
{
    string a;
    cin>>a;
    cout<<eval(a);
    return 0;
}