Pagini recente » Cod sursa (job #2711368) | Cod sursa (job #2596895) | Cod sursa (job #2312905) | Cod sursa (job #1481183) | Cod sursa (job #3182313)
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
int eval(const int num1, const int num2, const char op) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num2 - num1;
case '*':
return num1 * num2;
case '/':
return num2 / num1;
default:
return 0;
}
}
int nextNum(const std::string &expression, size_t &pos) {
int number = 0;
while (pos < expression.size() && expression[pos] >= '0' && expression[pos] <= '9') {
number = number * 10 + (expression[pos] - '0');
++pos;
}
return number;
}
bool priority(const char op1, const char op2) {
if (op1 == '(') {
return true;
}
if (op1 == '-' || op1 == '+') {
return op2 == '*' || op2 == '/';
}
return false;
}
void solve(const std::string &expression) {
std::ofstream fout("evaluare.out");
std::stack<char> operators;
std::stack<int> operands;
size_t size = expression.size();
size_t i = 0;
while (i < size) {
switch (expression[i]) {
case '(':
operators.push(expression[i++]);
break;
case ')':
while (operators.top() != '(') {
int first = operands.top();
operands.pop();
int second = operands.top();
operands.pop();
operands.push(eval(first, second, operators.top()));
operators.pop();
}
operators.pop();
i++;
break;
case '+':
case '-':
case '*':
case '/':
if (operators.empty() || priority(operators.top(), expression[i])) {
operators.push(expression[i++]);
} else {
do {
int first = operands.top();
operands.pop();
int second = operands.top();
operands.pop();
operands.push(eval(first, second, operators.top()));
operators.pop();
} while (!operators.empty() && !priority(operators.top(), expression[i]));
operators.push(expression[i++]);
}
break;
default:
operands.push(nextNum(expression, i));
}
}
while (!operators.empty()) {
int first = operands.top();
operands.pop();
int second = operands.top();
operands.pop();
operands.push(eval(first, second, operators.top()));
operators.pop();
}
fout << operands.top();
}
int main() {
std::ifstream fin("evaluare.in");
std::string expression;
getline(fin, expression);
solve(expression);
return 0;
}