Cod sursa(job #2278972)

Utilizator tangerine515Alex Anton tangerine515 Data 8 noiembrie 2018 19:33:41
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <fstream>
#include <cctype>
#include <string>
#include <stack>
#include <vector>

std::fstream fi("expresie.in", std::ios::in);
std::fstream fo("expresie.out", std::ios::out);

static int prioritate(char op) {
    if (op == '+' || op == '-')
        return 1;
    if (op == '*' || op == '/')
        return 2;

    return 0;
}

static int rezolva(int a, int b, char op) {
    switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
    }
}

static int evaluare(std::string tok) {
    std::stack<int>     val;
    std::stack<int>     op;

    for (unsigned i = 0; i < tok.length(); ++i) {
        if (tok.at(i) == ' ')
            continue;
        else if (tok.at(i) == '(')
            op.push(tok.at(i));
        else if (std::isdigit(tok.at(i))) {
            int v = 0;

            while (i < tok.length() && std::isdigit(tok.at(i)))
                v = (v * 10) + (tok.at(i++) - 48);
            
            if (i < tok.length())
                if (!isdigit(tok.at(i)) && tok.at(i) != ' ') --i;

            val.push(v);
        }
        else if (tok.at(i) == ')') {
            while (!op.empty() && op.top() != '(') {
                int b = val.top(); val.pop();
                int a = val.top(); val.pop();

                char o = op.top(); op.pop();

                val.push(rezolva(a, b, o));
            }
            
            op.pop();
        } else {
            while (!op.empty() && prioritate(op.top()) >= prioritate(tok.at(i))) {
                int b = val.top(); val.pop();
                int a = val.top(); val.pop();

                char o = op.top(); op.pop();

                val.push(rezolva(a, b, o));
            }

            op.push(tok.at(i));
        }
    }

    while (!op.empty()) {
        int b = val.top(); val.pop();
        int a = val.top(); val.pop();

        char o = op.top(); op.pop();

        val.push(rezolva(a, b, o));
    }

    return val.top();
}

int main() {
    std::string expr;
    std::getline(fi, expr);

    fo << evaluare(expr);
    return 0;
}