Pagini recente » Cod sursa (job #3200498) | Cod sursa (job #7348) | Cod sursa (job #557315) | Cod sursa (job #2249952) | Cod sursa (job #2591697)
#include <bits/stdc++.h>
#define ps push
using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
bool priority (char x, char y)
{
if (x == '(')
return true;
if ((x == '-' || x == '+') && (y == '*' || y == '/'))
return true;
return false;
}
int main ()
{
string a;
string p;
stack <char> st;
getline (fin, a);
for (int j = 0; j < a.size (); j++)
{
char i = a[j];
if (i == ' ')
continue;
else
{
if (!isdigit (i))
{
if (i == '(')
st.push (i);
else if (i == ')')
{
while (st.top () != '(')
{
p += st.top ();
st.pop ();
}
st.pop ();
}
else if (!st.empty ())
{
while (!priority (st.top (), i) && !st.empty ())
{
p += st.top ();
st.pop ();
}
st.ps (i);
}
else
st.ps (i);
}
else
{
if (isdigit (a[j - 1]))
p += i;
else
{
p += ' ';
p += i;
}
}
}
}
while (!st.empty ())
{
p += st.top ();
st.pop ();
}
int nr = 0;
stack <int> s;
for (int i = 0; i < p.size (); i++)
{
if (isdigit (p[i]))
nr = nr * 10 + p[i] - '0';
else
{
if (isdigit (p[i - 1]))
{
s.ps (nr);
nr = 0;
}
if (p[i] != ' ')
{
int x, y;
y = s.top ();
s.pop ();
x = s.top ();
s.pop ();
if (p[i] == '+')
s.ps (x + y);
else if (p[i] == '-')
s.ps (x - y);
else if (p[i] == '*')
s.ps (x * y);
else
s.ps (x / y);
}
}
}
fout << s.top ();
}