Pagini recente » Cod sursa (job #2137646) | Cod sursa (job #2047809) | Cod sursa (job #2171199) | Cod sursa (job #1488211) | Cod sursa (job #1990869)
#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;
}