Cod sursa(job #2223855)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 21 iulie 2018 20:27:06
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <string>
#include <cctype>

using namespace std;

const string IN_FILE = "evaluare.in";
const string OUT_FILE = "evaluare.out";

class Evaluator {
  public:
    Evaluator(const string expression) : exp(expression) {}

    int evaluate() {
        p = 0;
        return expression();
    }
  private:
    string exp;
    int p;

    int expression() {
        int value = term();
        while (p < int(exp.length()) && (exp[p] == '+' || exp[p] == '-')) {
            value = exp[p++] == '+' ? value + term() : value - term();
        }
        return value;
    }

    int term() {
        int value = factor();
        while (p < int(exp.length()) && (exp[p] == '*' || exp[p] == '/')) {
            value = exp[p++] == '*' ? value * factor() : value / factor();
        }
        return value;
    }

    int factor() {
        if (exp[p] == '(') {
            p++;
            const int value = expression();
            p++;
            return value;
        }
        int sign = 1;
        if (exp[p] == '-') {
            sign = -1;
            p++;
        }
        int value = 0;
        while (p < int(exp.length()) && isdigit(exp[p])) {
            value = value * 10 + exp[p++] - '0';
        }
        return sign * value;
    }
};

string readInput() {
    ifstream in(IN_FILE);
    string exp;
    in >> exp;
    in.close();
    return exp;
}

void writeOutput(const int result) {
    ofstream out(OUT_FILE);
    out << result << "\n";
    out.close();
}

int main() {
    const string exp = readInput();
    const int result = Evaluator(exp).evaluate();
    writeOutput(result);
    return 0;
}