Pagini recente » Cod sursa (job #1314493) | Cod sursa (job #2347673) | Cod sursa (job #504109) | Cod sursa (job #2481964) | Cod sursa (job #2157534)
#include <iostream>
#include <fstream>
#include <stack>
#include <string.h>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
int n, pr[256];
stack<char> op;
stack<int> var;
void calc() {
char o = op.top(); op.pop();
int b = var.top(); var.pop();
int a = var.top(); var.pop();
int r = 0;
if (o == '+') {
r = a + b;
} else if (o == '-') {
r = a - b;
} else if (o == '*') {
r = a * b;
} else {
r = a / b;
}
var.push(r);
}
int main()
{
pr['+'] = pr['-'] = 1;
pr['*'] = pr['/'] = 2;
pr['('] = 0;
int nr = 0;
int last = '$';
char c;
while (in >> c) {
if (!isdigit(c) && isdigit(last)) {
var.push(nr);
nr = 0;
}
if (isdigit(c)) {
nr = nr * 10 + (c - '0');
} else if (c == '(') {
op.push(c);
} else if (c == ')') {
while (op.top() != '(') calc();
op.pop();
} else {
while (!op.empty() && pr[c] <= pr[op.top()]) calc();
op.push(c);
}
last = c;
}
if (nr) var.push(nr);
while (!op.empty()) calc();
out << var.top();
return 0;
}