Cod sursa(job #2002180)

Utilizator epermesterNagy Edward epermester Data 18 iulie 2017 22:04:45
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 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)) {
			long 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 '+':
					if (!operators.empty()) {
						if (operators.top() == '-') {
							postfix.insert(postfix.end(), 1, ' ');
							postfix.insert(postfix.end(), 1, '-');
							operators.pop();
						}
						operators.push(*p);
						break;
					}
				case '-':
					if(!operators.empty())
					if (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<long> numbers;
	while (!pf.eof()){
		string temp;
		pf >> temp;
		if (temp[0] <= 57 && temp[0] >= 48) numbers.push(stol(temp));
		else {
			long c = numbers.top();
			numbers.pop();
			switch (temp[0])
				{
				case('+'):
					c += numbers.top();	break;
				case('-'):
					c = numbers.top()-c; break;
				case('*'):
					c *= numbers.top();	break;
				case('/'):
					if(c) c = numbers.top()/c;
					else c = numbers.top();
					break;
				}	
			numbers.pop();
			numbers.push(c);
		}
	}
	ofstream out("evaluare.out");
	out<<numbers.top();
}