Cod sursa(job #1990869)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 13 iunie 2017 22:54:34
Problema Evaluarea unei expresii Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
#include <iostream>
#include <fstream>
#include <string>
#include <list>

struct Operator {
    Operator() {}
    Operator(std::string op, int rank) : op(op), rank(rank) {}
    std::string op;
    int rank;
};

int main() {
    std::ifstream fileIn("evaluare.in");
    std::ofstream fileOut("evaluare.out");

    std::string expr, aux;

    std::list<std::string> post;
    std::list<Operator> opStack;

    fileIn >> expr;

    Operator opAux;

    for (int i(0); i < expr.length();) {
        if (expr[i] >= '0' && expr[i] <= '9') {
            aux = "";
            while (i < expr.length() && (expr[i] >= '0' && expr[i] <= '9')) {
                aux += expr[i];
                i++;
            }
            post.push_back(aux);
        } else if (expr[i] == ')') {
            while (opStack.back().op != "(") {
                post.push_back(opStack.back().op);
                opStack.pop_back();
            }
            opStack.pop_back();
            i++;
        } else if (expr[i] == '(') {
            opStack.push_back(Operator("(", 0));
            i++;
        } else {
            opAux = Operator();
            opAux.op = expr[i];
            opAux.rank = 2;
            if (expr[i] == '+' || expr[i] == '-') {
                opAux.rank = 1;
            }
            while (!opStack.empty() && opStack.back().rank >= opAux.rank) {
                post.push_back(opStack.back().op);
                opStack.pop_back();
            }
            opStack.push_back(opAux);
            i++;
        }
    }

    while (!opStack.empty()) {
        post.push_back(opStack.back().op);
        opStack.pop_back();
    }

    std::list<int> elem;
    int a, b;
    for (std::string curr : post) {
        std::cout << curr << ' ';
        if (curr[0] >= '0' && curr[0] <= '9') {
            elem.push_back(std::stoi(curr));
        } else {
            b = elem.back();
            elem.pop_back();
            a = elem.back();
            elem.pop_back();
            if (curr[0] == '+') {
                elem.push_back(a + b);
            } else if (curr[0] == '-') {
                elem.push_back(a - b);
            } else if (curr[0] == '*') {
                elem.push_back(a * b);
            } else {
                elem.push_back(a / b);
            }
        }
    }

    fileOut << elem.back();

    fileIn.close();
    fileOut.close();
    return 0;
}