Pagini recente » Cod sursa (job #2086045) | Cod sursa (job #2455781) | Cod sursa (job #2851024) | Cod sursa (job #1828551) | Cod sursa (job #2675387)
#include <fstream>
#include <vector>
using namespace std;
int pr(char c)
{
if(c=='(' || c==')')
return 0;
if(c=='*' || c=='/')
return 1;
if(c=='+' || c=='-')
return 2;
}
vector<char> fp;
vector<char> st;
vector<int> st2;
int main()
{
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
char x,a,b,cnt=0;
int n=0,na,nb;
string s;
cin >> s;
for(int i=0;i<s.size();i++)
{
x=s[i];
if('0'<=x && x<='9')
{
fp.push_back(x);
continue;
}
else
{
fp.push_back(' ');
st.push_back(x);
}
if(st.size()>=2 && pr(st.back())==1)
{
b=st.back();
st.pop_back();
a=st.back();
if(pr(a)==1)
{
fp.push_back(a);
fp.push_back(' ');
st.pop_back();
}
st.push_back(b);
}
if(st.size()>=2 && pr(st.back())==2)
{
b=st.back();
st.pop_back();
a=st.back();
if(pr(a)>=1)
{
fp.push_back(a);
fp.push_back(' ');
st.pop_back();
}
st.push_back(b);
}
if(st.size()>0 && st.back()==')')
{
st.pop_back();
while(1)
{
if(st.back()!='(')
{
fp.push_back(st.back());
fp.push_back(' ');
st.pop_back();
}
else
{
st.pop_back();
break;
}
}
}
}
while(st.size()>0)
{
fp.push_back(st.back());
st.pop_back();
}
cout << '\n';
int i=0;
while(i<fp.size())
{
while(fp[i]==' ')
{
i++;
}
if('0'<=fp[i] && fp[i]<='9')
{
while('0'<=fp[i] && fp[i]<='9')
{
n=n*10+(fp[i]-'0');
i++;
}
st2.push_back(n);
n=0;
}
else if(st2.size()>=2)
{
x=fp[i];
nb=st2.back();
st2.pop_back();
na=st2.back();
st2.pop_back();
if(x=='+')
st2.push_back(na+nb);
if(x=='-')
st2.push_back(na-nb);
if(x=='*')
st2.push_back(na*nb);
if(x=='/')
st2.push_back(na/nb);
i++;
}
}
cout << st2.back();
return 0;
}