Pagini recente » Cod sursa (job #2317831) | Cod sursa (job #847657) | Cod sursa (job #2329438) | Cod sursa (job #2365120) | Cod sursa (job #3266990)
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
int main()
{
fin >> s;
stack<int> st;
stack<char> op;
int i = 0;
while (s[i])
{
if (s[i] >= '0' && s[i] <= '9')
{
int nr = 0;
while (s[i] >= '0' && s[i] <= '9')
{
nr = nr * 10 + s[i] - '0';
i++;
}
st.push(nr);
}
if (s[i] == ')')
{
while (op.top() != '(')
{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
switch (op.top())
{
case '+':
st.push(a + b);
break;
case '-':
st.push(b - a);
break;
case '*':
st.push(a * b);
break;
case '/':
st.push(b / a);
break;
default:
break;
}
op.pop();
}
op.pop();
}
else if (s[i])
{
if (s[i] == '+' || s[i] == '-')
while (!op.empty() && (op.top() == '*' || op.top() == '/'))
{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
if (op.top() == '*')
st.push(a * b);
else
st.push(b / a);
op.pop();
}
op.push(s[i]);
}
i++;
}
while (!op.empty())
{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
switch (op.top())
{
case '+':
st.push(a + b);
break;
case '-':
st.push(b - a);
break;
case '*':
st.push(a * b);
break;
case '/':
st.push(b / a);
break;
default:
break;
}
op.pop();
}
fout << st.top() << '\n';
return 0;
}