Pagini recente » Cod sursa (job #1053029) | Cod sursa (job #2346863) | Cod sursa (job #1522263) | Cod sursa (job #2346865) | Cod sursa (job #3346611)
#include <bits/stdc++.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string s;
stack<char> op;
stack <int> nr;
int i=0;
int calc()
{
int r=nr.top();
nr.pop();
while(!op.empty()&&!nr.empty())
{
while(op.top()=='('||op.top()==')')
op.pop();
char oper=op.top();
if(oper=='*')
r*=nr.top();
else if(oper=='/')
r=nr.top()/r;
else if(oper=='+')
r+=nr.top();
else if(oper=='-')
r=nr.top()-r;
nr.pop();
op.pop();
}
while(!op.empty())
op.pop();
return r;
}
int getnr()
{
int r=0;
while(s[i]>='0'&&s[i]<='9')
r*=10, r+=s[i]-'0', i++;
i--;
return r;
}
void afis(stack<char> a, stack<int> b)
{
while(!a.empty())
cout << a.top() << " ", a.pop();
cout << '\n';
while(!b.empty())
cout << b.top() << " ", b.pop();
cout << "\n-------------------\n";
}
int main()
{
f >> s;
while(i<s.size())
{
if(s[i]>='0'&&s[i]<='9')
nr.push(getnr());
else
{
if(!op.empty()&&(s[i]=='+'||s[i]=='-')&&(op.top()=='*'||op.top()=='/'))
{
nr.push(calc());
i--;
}
else if(s[i]==')')
nr.push(calc());
else
{
op.push(s[i]);
}
}
//afis(op, nr);
i++;
}
nr.push(calc());
g << nr.top();
return 0;
}