#include <fstream>
#include <stack>
using namespace std;
bool hasPrecedence(char op1, char op2);
int processNextValues(stack<int> &valueStack, stack<char> &opStack);
int main()
{
stack<int> valueStack;
stack<char> opStack;
char c;
char lastRead = 'a';
int nr;
ifstream f("evaluare.in");
bool firstRead = true;
while (f >> c)
{
if (c == '-')
{
if (firstRead)
c = 'u';
else if (lastRead == '(')
c = 'u';
else if (lastRead == '+' || lastRead == '-' || lastRead == '*' || lastRead == '/')
c = 'u';
}
if (c >= '0' && c <= '9')
{
if (lastRead >= '0' && lastRead <= '9')
{
nr = valueStack.top(), valueStack.pop();
nr = nr * 10 + (c - '0');
valueStack.push(nr);
}
else
valueStack.push(c - '0');
}
else if (c == '(' || c == 'u')
opStack.push(c);
else if (c == '*' || c == '/' || c == '+' || c == '-')
{
while (!opStack.empty() && hasPrecedence(opStack.top(), c))
valueStack.push(processNextValues(valueStack, opStack));
opStack.push(c);
}
else if (c == ')')
{
while (opStack.top() != '(')
valueStack.push(processNextValues(valueStack, opStack));
opStack.pop();
if (!opStack.empty() && opStack.top() == 'u')
{
nr = valueStack.top(), valueStack.pop();
valueStack.push(-nr);
opStack.pop();
}
}
lastRead = c;
firstRead = false;
}
f.close();
while (!opStack.empty())
valueStack.push(processNextValues(valueStack, opStack));
ofstream g("evaluare.out");
g<< valueStack.top();
g.close();
return 0;
}
bool hasPrecedence(char op1, char op2)
{
if (op1 == 'u')
return true;
else if (op1 == '(')
return false;
else if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/'))
return false;
return true;
}
int processNextValues(stack<int> &valueStack, stack<char> &opStack)
{
char sign = opStack.top();
opStack.pop();
int operand2 = valueStack.top();
valueStack.pop();
if (sign == 'u')
return -operand2;
int operand1 = valueStack.top();
valueStack.pop();
switch (sign)
{
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
}
}