Cod sursa(job #984283)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 13 august 2013 23:30:39
Problema Evaluarea unei expresii Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include <fstream>
#include <string>
#include <sstream>
#include <stack>

void parse(std::string& str, std::string& n)
{
	std::stack<char> myS;
	std::stringstream nstr;
	for(int i = 0; i < str.length();)
	{
		if(str[i] == '(') myS.push('(');
		else if(str[i] == ')')
		{
			while(myS.top() != '(')
			{
				nstr << myS.top();
				nstr << ' ';
				myS.pop();
			}
			myS.pop();
		}
		else if(str[i] == '+' || str[i] == '-')
		{
			while(!myS.empty() && myS.top() != '(')
			{
				nstr << myS.top();
				nstr << ' ';
				myS.pop();
			}
			myS.push(str[i]);
		}
		else if(str[i] == '*' || str[i] == '/')
		{
			while(!myS.empty() && myS.top() != '(' && myS.top() != '+' && myS.top() != '-')
			{
				nstr << myS.top();
				nstr << ' ';
				myS.pop();
			}
			myS.push(str[i]);
		}
		else
		{
			while(str[i] >= '0' && str[i] <= '9')
			{
				nstr << str[i];
				i++;
			}
			nstr << ' ';
			continue;
		}
		i++;
	}
	while(!myS.empty())
	{
		nstr << myS.top();
		nstr << ' ';
		myS.pop();
	}
	getline(nstr, n);
}

long long reg(std::string& str)
{
	std::stack<int> myS;
	int a, b;
	for(int i = 0; i < str.length();)
	{
		if(str[i] >= '0' && str[i] <= '9')
		{
			std::stringstream nr;
			while(str[i] >= '0' && str[i] <= '9')
			{
				nr << str[i];
				i++;
			}
			nr >> a;
			myS.push(a);
			continue;
		}
		else if(str[i] == '+')
        {
            b = myS.top();
            myS.pop();
            a = myS.top();
            myS.pop();
            myS.push(a + b);
        }
        else if(str[i] == '-')
        {
            b = myS.top();
            myS.pop();
            a = myS.top();
            myS.pop();
            myS.push(a - b);
        }
        else if(str[i] == '*')
        {
            b = myS.top();
            myS.pop();
            a = myS.top();
            myS.pop();
            myS.push(a * b);
        }
        else if(str[i] == '/')
        {
            b = myS.top();
            myS.pop();
            a = myS.top();
            myS.pop();
            myS.push(a / b);
        }
        i++;
	}
	return myS.top();
}

int main()
{
	std::ifstream in("evaluare.in");
	std::ofstream out("evaluare.out");
	std::string str, nstr;
	getline(in, str);
	parse(str, nstr);
	out << reg(nstr);
	return 0;
}