Pagini recente » Cod sursa (job #2845152) | Cod sursa (job #1627668) | Cod sursa (job #2931536) | Cod sursa (job #1693208) | Cod sursa (job #2564624)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string sir;
stack < int > val;
stack < char > op;
map < char, int > m;
int Calc(char o, int a, int b)
{
switch (o)
{
case '+' :
return a + b;
case '-' :
return a - b;
case '*' :
return a * b;
case '/' :
return a / b;
}
}
int main()
{
fin >> sir;
m['*'] = 10;
m['/'] = 10;
m['+'] = 1;
m['-'] = 1;
m['('] = -1;
bool g;
for(int i = 0; i < sir.length(); i++)
{
if (sir[i] == '(')
{
g = 0;
op.push('(');
}
else if (sir[i] == ')')
{
if (g)
{
while (!op.empty() && op.top() != '(')
{
char o = op.top();
op.pop();
int a = val.top();
val.pop();
int b = val.top();
val.pop();
val.push(Calc(o, b, a));
}
}
if (!op.empty())
op.pop();
}
else if (isdigit(sir[i]))
{
int nr = 0;
while (isdigit(sir[i]))
{
nr = nr * 10 + sir[i] - '0';
i++;
}
i--;
val.push(nr);
}
else
{
g = 1;
if (!op.empty() && m[op.top()] >= m[sir[i]])
{
char o = op.top();
op.pop();
int a = val.top();
val.pop();
int b = val.top();
val.pop();
val.push(Calc(o, b, a));
}
op.push(sir[i]);
}
}
while (!op.empty())
{
char o = op.top();
op.pop();
int a = val.top();
val.pop();
int b = val.top();
val.pop();
val.push(Calc(o, b, a));
}
fout << val.top();
fin.close();
fout.close();
return 0;
}