Cod sursa(job #2006725)

Utilizator epermesterNagy Edward epermester Data 31 iulie 2017 13:53:16
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <fstream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;

int main() {
	ifstream in("evaluare.in");
	char infix[100000];
	in >> infix;

	stack<char> operators;
	string postfix;


	char *p = infix;
	while (*p) {
		if (isdigit(*p)) {
			double val = strtol(p, &p, 0);
			postfix.insert(postfix.end() - postfix.begin(), ' ' + to_string(val));
			if (!operators.empty())
				if (operators.top() == '-') {
					postfix.insert(postfix.end(), 1, ' ');
					postfix.insert(postfix.end(), 1, '-');
					operators.pop();
				}
		}

		else {
			switch (*p)
			{
			case '+':
			case '-':
				if (!operators.empty())
					if (operators.top() == '*' || operators.top() == '/' || operators.top() == '-')
						while (operators.top() != '(') {
							postfix.insert(postfix.end(), 1, ' ');
							postfix.insert(postfix.end(), 1, operators.top());
							operators.pop();
							if (operators.empty()) break;
						}
				operators.push(*p);
				break;

			case ')':
				while (operators.top() != '(')
				{
					postfix.insert(postfix.end(), 1, ' ');
					postfix.insert(postfix.end(), 1, operators.top());
					operators.pop();
				}
				operators.pop();
				break;

			default:
				operators.push(*p);
				break;
			}
			p++;
		}
	}
	while (!operators.empty())
	{
		postfix.insert(postfix.end(), 1, ' ');
		postfix.insert(postfix.end(), 1, operators.top());
		operators.pop();
	}

	istringstream pf(postfix);
	stack<double> numbers;
	long oszto = 0;
	while (!pf.eof()) {
		string temp;
		pf >> temp;
		if (temp[0] <= 57 && temp[0] >= 48) numbers.push(stol(temp));
		else {
			double c = numbers.top();
			numbers.pop();
			switch (temp[0])
			{
			case('+'):
				if (oszto) {
					c /= oszto;
					oszto = 0;
				}
				c += numbers.top(); 
				break;
			case('-'):
				if (oszto) {
					c /= oszto;
					oszto = 0;
				}
				c = numbers.top() - c; 
				break;
			case('*'):
				c *= numbers.top(); 
				if (oszto) {
					if (c / oszto)
						c /= oszto;
						oszto = 0;
					}
					break;
			case('/'):
				if (numbers.top()/c) c = numbers.top() / c;
				else oszto = c;
				break;
			}
			numbers.pop();
			numbers.push(c);
		}
	}
	ofstream out("evaluare.out");
	out << postfix << endl;
	out << numbers.top();
}