Pagini recente » Cod sursa (job #807136) | Cod sursa (job #1059440) | Cod sursa (job #1395199) | Cod sursa (job #1278965) | Cod sursa (job #2063551)
#include <fstream>
#include <stack>
#include <queue>
#include <string>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char s[100005];
int i,n;
double nr;
stack <char> st;
stack <double> stn;
queue <string> fp;
string aux;
int prioritate(char o)
{
switch(o)
{
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
}
return 0;
}
void adaugaElement(char c)
{
aux.clear();
aux.push_back(c);
fp.push(aux);
}
void operatie(char o)
{
double x=stn.top(); stn.pop();
double y=stn.top(); stn.pop();
switch(o)
{
case '+': stn.push(x+y);break;
case '-': stn.push(y-x);break;
case '*': stn.push(x*y);break;
case '/': stn.push(y/x);break;
}
}
int main()
{
f>>s;
//toate parantezele devin rotunde
for(i=0;s[i];++i)
if(s[i]=='{' || s[i]=='[') s[i]='(';
else if(s[i]=='}' || s[i]==']') s[i]=')';
//adaug prima paranteza deschisa in stiva
st.push('(');
for(i=0;s[i];++i)
if(s[i]=='(') st.push(s[i]); //paranteza
else
if(s[i]>='0' && s[i]<='9') //numar
{
aux.clear();
while(s[i]>='0' && s[i]<='9')
{
aux.push_back(s[i]);
i++;
}
fp.push(aux);
--i;
}
else
if(s[i]==')')
{
while(st.top()!='(')
{
adaugaElement(st.top());
st.pop();
}
st.pop();
}
else //operator
{
while(prioritate(st.top())>prioritate(s[i]))
{
adaugaElement(st.top());
st.pop();
}
st.push(s[i]);
}
//sfarsit => extrag tot din stiva si pun in fp
while(st.top()!='(')
{
adaugaElement(st.top());
st.pop();
}
// calculul valorii expresiei
while(!fp.empty())
{
aux=fp.front();
if(aux[0]>='0' && aux[0]<='9')
{
//sir de caractere => numar
nr=0;
n=aux.length();
for(i=0;i<n;++i) nr=nr*10+(aux[i]-'0');
stn.push(nr);
}
else
operatie(aux[0]);
fp.pop();
}
g<<stn.top();
f.close();g.close();
return 0;
}