Pagini recente » Cod sursa (job #1476302) | Cod sursa (job #1432807) | Cod sursa (job #2548873) | Cod sursa (job #1545754) | Cod sursa (job #667386)
Cod sursa(job #667386)
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
ofstream out("evaluare.out");
int comp(int a, int b, int c)
{
out << a << " " << c << " " << b << "\n";
if(a==0&&c=='/')
return 0;
switch (c)
{
case '+': return (b+a);
case '-': return (b-a);
case '/': return (b/a);
case '*': return (b*a);
}
}
int main()
{
string str;
stack <int> postfix;
stack <char> ops;
ifstream in("evaluare.in");
getline (in, str);
in.close();
int i = -1;
while ((++i) < str.size())
{
if(str[i]=='+')
{
if(!ops.empty())
{
while(ops.top()=='*'||ops.top()=='/'||ops.top()=='-')
{
int a = postfix.top();
postfix.pop();
int b = postfix.top();
postfix.pop();
postfix.push(comp(a,b,ops.top()));
ops.pop();
if(ops.empty())
break;
}
}
ops.push('+');
}
else
if(str[i]=='-')
{
if(!ops.empty())
{
while(ops.top()=='*'||ops.top()=='/'||ops.top()=='+')
{
int a = postfix.top();
postfix.pop();
int b = postfix.top();
postfix.pop();
postfix.push(comp(a,b,ops.top()));
ops.pop();
if(ops.empty())
break;
}
}
ops.push('-');
}
else
if(str[i]=='*')
{
if(!ops.empty())
{
if(ops.top()=='/')
{
int a = postfix.top();
postfix.pop();
int b = postfix.top();
postfix.pop();
postfix.push(comp(a,b,'/'));
ops.pop();
if(ops.empty())
break;
}
}
ops.push('*');
}
else
if(str[i]=='/')
{
if(!ops.empty())
{
while(ops.top()=='*'||ops.top()=='/')
{
int a = postfix.top();
postfix.pop();
int b = postfix.top();
postfix.pop();
postfix.push(comp(a,b,ops.top());
ops.pop();
if(ops.empty())
break;
}
}
ops.push('/');
}
else
if(str[i]=='(')
{
ops.push('(');
}
else
if(str[i]==')')
{
while(ops.top()!='(')
{
int a = postfix.top();
postfix.pop();
int b = postfix.top();
postfix.pop();
postfix.push(comp(a,b,ops.top()));
ops.pop();
}
ops.pop();
}
else
{
int temp = 0;
while(str[i]>=48 && str[i]<=57)
{
temp = temp*10 + (str[i] - 48);
++i;
}
--i;
postfix.push(temp);
}
}
while(!ops.empty())
{
int a = postfix.top();
postfix.pop();
int b = postfix.top();
postfix.pop();
postfix.push(comp(a,b,ops.top()));
ops.pop();
}
out << postfix.top();
out.close();
return 0;
}