Cod sursa(job #2348998)

Utilizator filicriFilip Crisan filicri Data 20 februarie 2019 09:26:30
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#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;
}