Cod sursa(job #2002020)

Utilizator epermesterNagy Edward epermester Data 18 iulie 2017 13:41:18
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 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));
		}
		else {
			switch (*p)
			{
				case '+':
				case '-':
					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 = 0;
			switch (temp[0])
				{
				case('+'):
					c += numbers.top();
					numbers.pop();
					c += numbers.top();
					numbers.pop();
					numbers.push(c);
					break;
				case('-'):
					c -= numbers.top();
					numbers.pop();
					c += numbers.top();
					numbers.pop();
					numbers.push(c);
					break;
				case('*'):
					c = numbers.top();
					numbers.pop();
					c = numbers.top()*c;
					numbers.pop();
					numbers.push(c);
					break;
				case('/'):
					c = numbers.top();
					numbers.pop();
					c = numbers.top()/c;
					numbers.pop();
					numbers.push(c);
					break;
				default:
					break;
				}	
		}
	}
	ofstream out("evaluare.out");
	out<<numbers.top();
}