Pagini recente » Cod sursa (job #1411781) | Cod sursa (job #2609669) | Cod sursa (job #1085088) | Cod sursa (job #2626220) | Cod sursa (job #3242463)
// polish form
#include <fstream>
#include <string>
#include <stack>
int main()
{
std::ifstream cin("evaluare.in");
std::ofstream cout("evaluare.out");
std::string expr;
cin >> expr;
std::stack<int> values;
std::stack<char> operators;
auto perform_op = [&]()
{
int b = values.top();
values.pop();
int a = values.top();
values.pop();
char op = operators.top();
operators.pop();
if (op == '+')
values.push(a + b);
else if (op == '-')
values.push(a - b);
else if (op == '*')
values.push(a * b);
else if (op == '/')
values.push(a / b);
else
throw "Unknown operator";
};
auto precedence = [](char c)
{
if (c == '+' || c == '-')
return 1;
if (c == '*' || c == '/')
return 2;
if (c == '(')
return -1; // should never perform_op when the top of the operator stack is '('
throw "Unknown operator";
};
for (int i = 0; i < (int)expr.size(); i++)
{
if (isdigit(expr[i])) // number
{
int number = 0;
while (i < (int)expr.size() && isdigit(expr[i]))
{
number = number * 10 + (expr[i] - '0');
++i;
}
--i; // for loop will increment i
values.push(number);
}
else if (expr[i] == '(') // open subexpression
{
operators.push('(');
}
else if (expr[i] == ')') // close subexpression
{
while (operators.top() != '(')
perform_op();
operators.pop(); // pop open parentheses
}
else // operator
{
while (!operators.empty() && precedence(operators.top()) >= precedence(expr[i]))
perform_op();
operators.push(expr[i]);
}
}
while (!operators.empty())
perform_op();
cout << values.top() << '\n';
return 0;
}