Pagini recente » Cod sursa (job #2781688) | Cod sursa (job #2640335) | Cod sursa (job #2329600) | Cod sursa (job #3247821) | Cod sursa (job #2348998)
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string s;
stack <int> vals;
stack <char> ops;
int calc (char op,int a, int b)
{
if (op=='+') return (a+b);
if (op=='-') return (a-b);
if (op=='*') return (a*b);
if (op=='/') return (a/b);
}
int prec (char op)
{
if (op=='+' || op=='-') return 1;
if (op=='*' || op=='/') return 2;
return 0;
}
void sol (void)
{
int x=vals.top();
vals.pop();
int y=vals.top();
vals.pop();
char op=ops.top();
ops.pop();
vals.push(calc(op,y,x));
}
int main()
{
f>>s;
for (int i=0;i<s.length();i++)
{
if (s[i]=='(') ops.push(s[i]);
else if (isdigit(s[i]))
{
int num=0;
while (i<s.length() && isdigit(s[i]))
{
num=num*10+(s[i]-'0');
i++;
}
i--;
vals.push(num);
}
else if (s[i]==')')
{
while (!ops.empty() && ops.top()!='(') sol();
ops.pop();
}
else
{
while (!ops.empty() && prec(ops.top())>=prec(s[i])) sol();
ops.push(s[i]);
}
}
while (!ops.empty()) sol();
g<<vals.top();
f.close();
g.close();
return 0;
}