Pagini recente » Cod sursa (job #448551) | Cod sursa (job #1104693) | Cod sursa (job #2221165) | Cod sursa (job #1425151) | Cod sursa (job #979300)
Cod sursa(job #979300)
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
stack<string> polish, out, aux;
stack<unsigned long int> num;
map<string, int> operators;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string expr, token;
bool lastNum = false;
char current;
unsigned long 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) {
string num = out.top();
out.pop();
out.push(num+current);
} else {
out.push(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) {
out.push(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() != "(") {
out.push(aux.top());
aux.pop();
}
aux.pop();
}
lastNum = false;
}
}
while (!aux.empty()) {
out.push(aux.top());
aux.pop();
}
while (!out.empty()) {
polish.push(out.top());
out.pop();
}
while (!polish.empty()) {
token = polish.top();
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()));
}
polish.pop();
}
fout<<num.top()<<"\n";
return 0;
}