Cod sursa(job #3286252)

Utilizator herbiHreban Antoniu George herbi Data 13 martie 2025 21:07:13
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <stack>

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack<int>numere;
stack<char>oper;

bool is_op(char c)
{
	if (c == '+' || c == '-' || c == '*' || c == '/')
		return 1;
	return 0;
}
int priority_operator(char c)
{
	if (c == '+' || c == '-')
		return 1;
	if (c == '*' || c == '/')
		return 2;
		return -1;
}
void process_op()
{
	int a = numere.top();
		numere.pop();
		int b = numere.top();
		numere.pop();
		char c = oper.top();
		if (c == '+')
			numere.push(a + b);
		else
		{
			if (c == '-')
				numere.push(b - a);
			else
			{
				if (c == '*')
					numere.push(a * b);
				else if(c=='/')
					numere.push(b / a);
			}
		}

}
int main()
{
	fin >> s;
	for (int i = 0; i < s.size(); i++)
	{
		
		if (s[i] == '(')
			oper.push('(');
		else
		{
			if (s[i] == ')')
			{
				while (oper.top() != '(')
				{
					process_op();
					oper.pop();
				}
				oper.pop();
			}
			else
			{
				if (is_op(s[i]))
				{
				
					char c = s[i];
					while (!oper.empty() && (priority_operator(oper.top()) >= priority_operator(c)))
					{	
						
						process_op();
						oper.pop();
					}
					oper.push(c);
				}
				else
				{
					int nr = 0;
					while (i < s.size() && isdigit(s[i]))
					{
						nr = nr * 10 + s[i] - '0';
						i++;
					}
					i--;
					numere.push(nr);
				}
			}
		}
	}
	while (!oper.empty())
	{
		process_op();
		oper.pop();
	}
	fout << numere.top();
	return 0;
}