Pagini recente » Cod sursa (job #2941015) | Cod sursa (job #1742610) | Cod sursa (job #2762980) | Cod sursa (job #551707) | Cod sursa (job #1591868)
#include<iostream>
#include<fstream>
#include<string>
#include<cctype>
#include<stack>
using namespace std;
fstream fin("evaluare.in",ios::in),fout("evaluare.out",ios::out);
stack<char> op;
stack<int> nr;
string s;
int p[200],ls;
int numar(int&i)
{
int num=0;
while(i<ls && isdigit(s[i]))
{
num=num*10+(s[i]-'0');
i++;
}
return num;
}
void calc(char oper)
{
int a,b,c;
b=nr.top();nr.pop();
a=nr.top();nr.pop();
if(oper=='-') nr.push(a-b);
if(oper=='+') nr.push(a+b);
if(oper=='/') nr.push(a/b);
if(oper=='*') nr.push(a*b);
}
int solv()
{
int i,j;
ls=s.size();
for(i=0;i<ls;i++)
{
if(isdigit(s[i]))
{
nr.push(numar(i));
i--;
}
else
{
if(s[i]=='(')
op.push('(');
else
{
if(s[i]==')')
{
while(op.top()!='(')
{
calc(op.top());
op.pop();
}
op.pop();
}
else
{
while(!op.empty() && p[op.top()]>=p[s[i]])
{
calc(op.top());
op.pop();
}
op.push(s[i]);
}
}
}
}
while(!op.empty())
{
calc(op.top());
op.pop();
}
return nr.top();
}
int main()
{
int i,j;
p['/']=2;
p['*']=2;
p['+']=1;
p['-']=1;
p['(']=0;
p[')']=0;
fin>>s;
fout<<solv();
}