Pagini recente » Cod sursa (job #1466874) | Cod sursa (job #769493) | Cod sursa (job #232094) | Cod sursa (job #1504324) | Cod sursa (job #3346618)
#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())
{
if(op.top()=='(')
{
op.pop();
break;
}
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();
}
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]);
if(op.top()=='*'||op.top()=='/')
{
i++;
nr.push(getnr());
nr.push(calc());
}
}
}
afis(op, nr);
i++;
}
nr.push(calc());
g << nr.top();
return 0;
}