Pagini recente » Cod sursa (job #304037) | Cod sursa (job #1994466) | testuletzzzz | Statistici FMI Mateescu Basil (amidazar) | Cod sursa (job #2169898)
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
ifstream fi("evaluare.in");
ofstream fo("evaluare.out");
char a[100001];
char b[100001];
char res[500005];
int k=-1;
bool operand(char exp)
{
if(exp>='0' and exp<='9')
return 1;
return 0;
}
bool operator_(char exp)
{
if(exp=='+' or exp=='-' or exp=='*' or exp=='/')
return 1;
return 0;
}
bool priority(char a, char exp)
{
if((exp=='+' or exp=='-') and (a=='*' or a=='/'))
return 1;
return 0;
}
void infix_postfix(char exp[100001])
{
stack <char> s;
for(int i=0;i<strlen(exp);i++)
{
if(operand(exp[i]))
{
while(exp[i]>='0' and exp[i]<='9' and i<=strlen(exp))
{
res[++k]=exp[i];
i++;
}
res[++k]=' ';
i--;
}
else if(operator_(exp[i]))
{
while(!s.empty() and s.top()!='(' and priority(s.top(),exp[i]))
{
res[++k]=s.top();
s.pop();
}
s.push(exp[i]);
fo<<s.top();
}
else if(exp[i]=='(')
s.push(exp[i]);
else if(exp[i]==')')
{
while(s.top()!='(')
{
res[++k]=s.top();
s.pop();
}
s.pop();
}
}
while(!s.empty())
{
res[++k]=s.top();
s.pop();
}
}
void evaluation()
{
stack <int> s;
int op;
for(int i=0;i<strlen(res);i++)
{
op=0;
if(operand(res[i]))
{
while(operand(res[i]))
{
op=op*10+(res[i]-'0');
i++;
}
i--;
s.push(op);
}
else if(operator_(res[i]))
{
int b=s.top();
s.pop();
int a=s.top();
s.pop();
if(res[i]=='+')
s.push(a+b);
if(res[i]=='-')
s.push(a-b);
if(res[i]=='*')
s.push(a*b);
if(res[i]=='/')
s.push(a/b);
}
}
fo<<s.top();
}
int main()
{
fi.getline(a,100001);
infix_postfix(a);
fo<<res;
evaluation();
return 0;
}