Pagini recente » Cod sursa (job #2617638) | Cod sursa (job #763687) | Cod sursa (job #3191211) | Cod sursa (job #2070578) | Cod sursa (job #3310621)
#include <iostream>
#include <stack>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
stack<int> S;
stack<char> op;
char s[100001];
char ope[] = "+-/*";
int Nr(char s[], int &i)
{
int nr = 0;
while (s[i] >= '0' && s[i] <= '9')
{
nr = nr * 10 + s[i] - '0';
i++;
}
i--;
return nr;
}
int Priority(char op)
{
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
void ApplyOp()
{
int a, b;
char Op;
b = S.top();
S.pop();
a = S.top();
S.pop();
Op = op.top();
op.pop();
if (Op == '+')
S.push(a + b);
if (Op == '-')
S.push(a - b);
if (Op == '*')
S.push(a * b);
if (Op == '/')
S.push(a / b);
}
int main()
{
fin.getline(s, 100001);
int i = 0;
int nr;
while (s[i] != '\0')
{
if (s[i] >= '0' && s[i] <= '9')
{
nr = Nr(s, i);
S.push(nr);
}
if (s[i] == '(')
{
op.push('(');
}
if (strchr(ope, s[i]) != NULL)
{
while (op.size() != 0 && Priority(op.top()) >= Priority(s[i]))
ApplyOp();
op.push(s[i]);
}
if (s[i] == ')')
{
while (op.top() != '(')
ApplyOp();
op.pop();
}
i++;
}
while (op.size() > 0)
ApplyOp();
fout << S.top();
return 0;
}