Pagini recente » Cod sursa (job #1886556) | Cod sursa (job #655901) | Cod sursa (job #3200508) | Cod sursa (job #2461218) | Cod sursa (job #3259535)
#include <bits/stdc++.h>
std::ifstream fin("evaluare.in");
std::ofstream fout("evaluare.out");
std::stack<int>s;
std::stack<char>operatii;
std::pair<int,int>numar(std::string ec,int i)
{
int ans=0;
while(i<ec.size()&&ec[i]>='0'&&ec[i]<='9')
{
ans=ans*10+(ec[i]-'0');
i++;
}
return {ans,--i};
}
void fa()
{
int x=s.top();
s.pop();
if(operatii.top()=='+')s.top()+=x;
else if(operatii.top()=='-')s.top()-=x;
else if(operatii.top()=='*')s.top()*=x;
else if(operatii.top()=='/')s.top()/=x;
operatii.pop();
}
bool mere(char op1, char op2)
{
if(op2=='(')return false;
if((op1=='+'||op1== '-')&&(op2=='*'||op2=='/'))return false;
return true;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::string ec;
fin>>ec;
for(int i=0;i<ec.length();i++)
{
if(ec[i]=='(')
{
operatii.push('(');
}
else if(ec[i]==')')
{
while(operatii.top()!='(')
{
fa();
}
operatii.pop();
}
else if(ec[i]>='0'&&ec[i]<='9')
{
auto[num,new_i]=numar(ec, i);
s.push(num);
i=new_i;
}
else if(ec[i]=='+'||ec[i]=='-'||ec[i]=='*'||ec[i]=='/')
{
while(!operatii.empty() && mere(ec[i],operatii.top()))
{
fa();
}
operatii.push(ec[i]);
}
}
while(!operatii.empty())
fa();
fout<<s.top();
return 0;
}