Pagini recente » Cod sursa (job #163303) | Cod sursa (job #2204918) | Cod sursa (job #1968251) | Cod sursa (job #433104) | Cod sursa (job #979311)
Cod sursa(job #979311)
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
stack<string> aux;
vector<string> polish;
stack<int> num;
map<string, int> operators;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string expr, token;
bool lastNum = false;
char current;
int result, a, b;
int main() {
fin>>expr;
operators["+"] = 0;
operators["-"] = 0;
operators["/"] = 5;
operators["*"] = 5;
for (unsigned int i = 0; i < expr.length(); ++i) {
current = expr.at(i);
if (current >= '0' && current <= '9') {
if (lastNum) {
polish[polish.size()-1] = polish.back()+current;
} else {
polish.push_back(string(1, current));
lastNum = true;
}
} else {
if (operators.find(string(1, current)) != operators.end()) {
while (!aux.empty() && (operators.find(aux.top()) != operators.end())) {
if (operators[string(1, current)] - operators[aux.top()] <= 0) {
polish.push_back(aux.top());
aux.pop();
continue;
}
break;
}
aux.push(string(1, current));
} else if (current == '(') {
aux.push(string(1, current));
} else if (current == ')') {
while (!aux.empty() && aux.top() != "(") {
polish.push_back(aux.top());
aux.pop();
}
aux.pop();
}
lastNum = false;
}
}
while (!aux.empty()) {
polish.push_back(aux.top());
aux.pop();
}
for (unsigned int i = 0; i < polish.size(); ++i) {
token = polish[i];
if (operators.find(token) != operators.end()) {
current = token.at(0);
b = num.top();
num.pop();
a = num.top();
num.pop();
switch (current) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
num.push(result);
} else {
num.push(atoi(token.c_str()));
}
}
fout<<num.top()<<"\n";
return 0;
}