Cod sursa(job #779114)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 16 august 2012 17:49:23
Problema Evaluarea unei expresii Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef __unix__
#include <unistd.h>
#else
#error "Unix specific library"
#endif

const unsigned int BUFFER_SIZE(100001);
char buffer [BUFFER_SIZE];
char *iterator(buffer);

signed int priority_one (void);
signed int priority_two (void);
signed int priority_three (void);

signed int priority_one (void)
{
	signed int result(priority_two());
	while (*iterator == '+' || *iterator == '-')
	{
		if (*iterator == '+')
		{
			++iterator;
			result += priority_two();
		}
		else
		{
			++iterator;
			result -= priority_two();
		}
	}
	return result;
}

signed int priority_two (void)
{
	unsigned int result(priority_three());
	while (*iterator == '*' || *iterator == '/')
	{
		if (*iterator == '*')
		{
			++iterator;
			result *= priority_three();
		}
		else
		{
			++iterator;
			result /= priority_three();
		}
	}
	return result;
}

signed int priority_three (void)
{
	unsigned int result(0);
	if (*iterator == '(')
	{
		++iterator;
		result = priority_one();
		++iterator;
	}
	else
		while (*iterator >= '0' && *iterator <= '9')
		{
			result *= 10;
			result += *iterator - '0';
			++iterator;
		}
	return result;
}

int main (void)
{
	int input(open("evaluare.in",O_RDONLY));
	read(input,buffer,BUFFER_SIZE);
	close(input);
	signed int result(priority_one());
	const unsigned int RESULT_SIZE(13);
	char result_string [RESULT_SIZE] = {0};
	bool negative(result < 0 ? true : false);
	if (negative)
		result = -result;
	unsigned int index(RESULT_SIZE - 2);
	do
	{
		result_string[index] = result % 10 + '0';
		result /= 10;
		--index;
	}
	while (result);
	if (negative)
		result_string[index] = '-';
	else
		++index;
	char *write_result(result_string + index);
	result_string[RESULT_SIZE - 1] = '\n';
	int output(open("evaluare.out",O_WRONLY | O_TRUNC | O_CREAT, 666));
	write(output,write_result,RESULT_SIZE - index);
	close(output);
	return 0;
}