Pagini recente » Cod sursa (job #2113382) | Cod sursa (job #375525) | Cod sursa (job #3173681) | Cod sursa (job #584164) | Cod sursa (job #1990875)
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
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");
freopen("evaluare.in", "r", stdin);
std::ofstream fileOut("evaluare.out");
//std::string expr;
std::string aux;
std::vector<std::string> post;
std::vector<Operator> opStack;
//fileIn >> expr;
char *expr = new char[100000];
gets(expr);
Operator opAux;
//for (int i(0); i < expr.length();) {
for (int i(0); i < strlen(expr);) {
if (expr[i] >= '0' && expr[i] <= '9') {
aux = "";
//while (i < expr.length() && (expr[i] >= '0' && expr[i] <= '9')) {
while (i < strlen(expr) && (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::vector<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;
}