Cod sursa(job #2833311)

Utilizator razvan99hHorhat Razvan razvan99h Data 15 ianuarie 2022 07:35:42
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

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

string expression;
int index;

int element();
int factor();

// will handle the content of an expression/subexpression - which consists of elements of an addition/subtraction
int evaluate() {
    int result = element();
    while (expression[index] == '+' || expression[index] == '-') {
        switch (expression[index]) {
            case '+':
                index ++;
                result += element();
                break;
            case '-':
                index ++;
                result -= element();
                break;
        }
    }
    return result;
}

// will handle the content of an element - which consists of factors of a multiplication/division
int element() {
    int result = factor();
    while (expression[index] == '*' || expression[index] == '/') {
        switch (expression[index]) {
            case '*':
                index ++;
                result *= factor();
                break;
            case '/':
                index ++;
                result /= factor();
                break;
        }
    }
    return result;
}

// will return the value of a single factor, which in turn can be a subexpression
int factor() {
    int result = 0;
    if (expression[index] == '(') { // we have a subexpression
        index ++;                   // we go over '('
        result = evaluate();        // evaluate the subexpression
        index ++;                   // we go over ')'
    } else {
        while (isdigit(expression[index])) {
            result = result * 10 + expression[index] - '0';
            index ++;
        }
    }
    return result;
}

int main()
{
    fin >> expression;
    fout << evaluate();

    return 0;
}