Cod sursa(job #2650698)

Utilizator bubblegumixUdrea Robert bubblegumix Data 19 septembrie 2020 18:59:59
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include<fstream>
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<stack>
using namespace std;
ifstream f("a.txt");
ofstream g("b.txt");
char expresie[300000],postfix[300000];
int p;

int prioritate(char c)
{
	if (strchr("+-", c))
		return 1;
	else
		if (strchr("*/", c))
			return 2;
		else
			return -10;


 }

bool isOperator(char c)
{
	if(strchr("()+-*/",c))
		return true;
	else
		return false;
}


void ordine_poloneza(char s[])
{
	stack <char> semne;
	semne.push('s');

	char* s1 = s;
	while (*s1 != '\0')
		if (isOperator(*s1))
		{
			if (*s1 == '(')
				semne.push(*s1);
			else
				if (*s1 == ')')
				{
					do
					{
						postfix[p++] = semne.top();
						postfix[p++] = ' ';
						semne.pop();
					} while (semne.top() != '(');
					semne.pop();
				}
				else
					if (prioritate(*s1) > prioritate(semne.top()))
						semne.push(*s1);
					else {
						while (semne.top() != 's' && prioritate(*s1) <= prioritate(semne.top()))
						{
							postfix[p++] = semne.top();
							postfix[p++] = ' ';
							semne.pop();
						}
						semne.push(*s1);
					}
			s1++;
		}
		else
		{
			while (!isOperator(*s1))
			{

				postfix[p++] = *s1;
				s1++;

			}
			postfix[p++] = ' ';

		}
	while (semne.top() != 's')
	{
		postfix[p++] = semne.top();
		postfix[p++] = ' ';
		semne.pop();
	}

	postfix[--p] = '\0';


}

int main()
{
	f.getline(expresie, 100);
	ordine_poloneza(expresie);
	char* next=NULL;
	char* cuv = strtok_s(postfix, " ", &next);
		stack <long long> stiva;

		while (cuv)
		{
			if (!isOperator(*cuv))
				stiva.push(atol (cuv));
			else
			{
				long long nod1 = stiva.top();
				stiva.pop();
				long long nod2 = stiva.top();
				stiva.pop();

				if (*cuv == '+')
					stiva.push(nod2 + nod1);
				else
					if (*cuv == '-')
						stiva.push(nod2 - nod1);
					else
						if (*cuv == '*')
							stiva.push(nod2 * nod1);
						else
							stiva.push(nod2 / nod1);
			}
			cuv = strtok_s(NULL, " ",&next);
		}
		g << stiva.top();




	f.close();
	g.close();
	return 0;
}