Cod sursa(job #2157534)

Utilizator savigunFeleaga Dragos-George savigun Data 9 martie 2018 18:19:42
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string.h>
using namespace std;

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

int n, pr[256];
stack<char> op;
stack<int> var;

void calc() {
    char o = op.top(); op.pop();
    int b = var.top(); var.pop();
    int a = var.top(); var.pop();
    int r = 0;

    if (o == '+') {
        r = a + b;
    } else if (o == '-') {
        r = a - b;
    } else if (o == '*') {
        r = a * b;
    } else {
        r = a / b;
    }

    var.push(r);
}

int main()
{
    pr['+'] = pr['-'] = 1;
    pr['*'] = pr['/'] = 2;
    pr['('] = 0;

    int nr = 0;
    int last = '$';
    char c;

    while (in >> c) {
        if (!isdigit(c) && isdigit(last)) {
            var.push(nr);
            nr = 0;
        }

        if (isdigit(c)) {
            nr = nr * 10 + (c - '0');
        } else if (c == '(') {
            op.push(c);
        } else if (c == ')') {
            while (op.top() != '(') calc();
            op.pop();
        } else {
            while (!op.empty() && pr[c] <= pr[op.top()]) calc();
            op.push(c);
        }

        last = c;
    }

    if (nr) var.push(nr);
    while (!op.empty()) calc();

    out << var.top();

    return 0;
}