Pagini recente » Cod sursa (job #813485) | Cod sursa (job #1330835) | Cod sursa (job #625847) | Cod sursa (job #1512700) | Cod sursa (job #2849205)
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <stack>
using namespace std;
stack <char> ops;
stack <int> valori;
int precedence(char op)
{
if (op == '+' or op == '-')
return 1;
if (op == '*' or op == '/')
return 2;
return 0;
}
int operatie(char op, int a, int b)
{
if (op == '+')
return a + b;
else if (op == '-')
return a - b;
else if (op == '*')
return a * b;
else if (op == '/')
return a / b;
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char c[100005], op;
int val2, val1, val;
fin.getline(c, 100005);
for (int i = 0; i < strlen(c); i++)
{
if (c[i] == ' ')
continue;
else if (c[i] == '(')
ops.push(c[i]);
else if (isdigit(c[i]))
{
val = 0;
while (i < strlen(c) and isdigit(c[i]))
{
val = val * 10 + (c[i] - '0');
i++;
}
valori.push(val);
i--;
}
else if (c[i] == ')')
{
while (!ops.empty() and ops.top() != '(')
{
val2 = valori.top();
valori.pop();
val1 = valori.top();
valori.pop();
op = ops.top();
ops.pop();
valori.push(operatie(op, val1, val2));
}
if (!ops.empty())
ops.pop();
}
else
{
while (!ops.empty() and precedence(ops.top()) >= precedence(c[i]))
{
val2 = valori.top();
valori.pop();
val1 = valori.top();
valori.pop();
op = ops.top();
ops.pop();
valori.push(operatie(op, val1, val2));
}
ops.push(c[i]);
}
}
while (!ops.empty())
{
val2 = valori.top();
valori.pop();
val1 = valori.top();
valori.pop();
op = ops.top();
ops.pop();
valori.push(operatie(op, val1, val2));
}
fout << valori.top();
return 0;
}