Cod sursa(job #1715190)

Utilizator mariusadamMarius Adam mariusadam Data 10 iunie 2016 04:22:03
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.57 kb
#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;

const char POSTFIX_DELIMITER = ',';
const string OPERATORS = "-+/*";

inline void appendToPostFix(string &postfix, const string & data) {
	postfix += data + POSTFIX_DELIMITER;
}

inline void appendToPostFix(string &postfix, const char & data) {
	postfix.push_back(data);
	postfix.push_back(POSTFIX_DELIMITER);
}

inline int priority(const char & op) {
	if (op == '-' || op == '+') {
		return 1;
	}
	if (op == '*' || op == '/') {
		return 2;
	}
	return 0;
}

inline bool isOperator(const string & op) {
	return OPERATORS.find(op) != string::npos;
}

inline bool isDigit(const char ch) {
	return (ch >= '0' && ch <= '9');
}

int perform(int a, int b, char op) {
	switch (op)	{
	case '-': return b - a;
	case '+': return b + a;
	case '*': return b * a;
	case '/': return b / a;
	default : return 0;
	}
}

void infix2postfix(string & infix, string & postfix) {
	stack<char> st;
	string number;
	char ch;
	unsigned int i = 0;
	int prec;
	postfix = "";
	while(i < infix.size()) {
		number = "";
		while (isDigit(infix[i])) {
			number += infix[i];
			i++;
		}
		if (number.empty() == false) {
			appendToPostFix(postfix, number);
			continue;
		}
		ch = infix[i];
		if (ch == '(') {
			st.push(ch);
			i++;
			continue;
		}
		if (ch == ')') {
			while (st.empty() == false && st.top() != '(') {
				appendToPostFix(postfix, st.top());
				st.pop();
			}
			if (st.empty() == false) {
				st.pop();
			}
			i++;
			continue;
		}
		
		if (st.empty()) {
			st.push(ch);
		}
		else {
			prec = priority(ch);
			while (st.empty() == false && st.top() != '(' && prec <= priority(st.top())) {
				appendToPostFix(postfix, st.top());
				st.pop();
			}
			st.push(ch);
		}
		i++;
	}
	while (st.empty() == false) {
		appendToPostFix(postfix, st.top());
		st.pop();
	}
}

int evaluatePostfix(string & postfix) {
	stack<int> operands;
	stringstream expr{ postfix };
	string aux;
	while (getline(expr, aux, POSTFIX_DELIMITER)) {
		if (isOperator(aux)) {
			int op1 = operands.top(); operands.pop();
			int op2 = operands.top(); operands.pop();
			char operatie = aux[0];
			operands.push(perform(op1, op2, operatie));
		}
		else {
			operands.push(atoi(aux.c_str()));
		}
	}
	return operands.top();
}

int main() {
	string infix, postfix;
	ifstream f("evaluare.in");
	f >> infix;
	f.close();
	infix2postfix(infix, postfix);
	ofstream g("evaluare.out");
	g << evaluatePostfix(postfix);
	g.close();
	return 0;
}