Cod sursa(job #2206869)

Utilizator heisenbugAnnoying Heisenbug heisenbug Data 24 mai 2018 02:13:00
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <iostream>

int get_op(char c)
{
    switch (c) {
    case '+':
    case '-':
        return 1;
    case '*':
    case '/':
        return 2;
    }
    return -1;
}

void pop_op(std::stack<char>& ops, std::stack<long>& nums)
{
    char op = ops.top();
    ops.pop();

    long b = nums.top();
    nums.pop();

    long a = nums.top();
    nums.pop();

    switch (op) {
    case '+':
        nums.push(a + b);
        break;
    case '-':
        nums.push(a - b);
        break;
    case '*':
        nums.push(a * b);
        break;
    case '/':
        nums.push(a / b);
        break;
    }
}

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

    std::string expr;
    std::getline(fin, expr);

    std::stack<char> ops;
    std::stack<long> nums;

    size_t i = 0;
    while (i < expr.size()) {
        if (expr[i] == '(') {
            ops.push('(');
            ++i;
        } else if (expr[i] == ')') {
            while (ops.top() != '(')
                pop_op(ops, nums);
            ops.pop();
            ++i;
        } else if (get_op(expr[i]) > 0) {
            while (ops.size() > 0 && get_op(ops.top()) > get_op(expr[i]))
                pop_op(ops, nums);
            ops.push(expr[i++]);
        } else {
            long n = 0;
            while (expr[i] >= '0' && expr[i] <= '9')
                n = n * 10 + (expr[i++] - '0');
            nums.push(n);
        }
    }

    while (ops.size() > 0)
        pop_op(ops, nums);

    fout << nums.top() << '\n';

    return 0;
}