Beispiel #1
0
ExpressionParser::ExpressionParser(const String & expression)
{
    _tokens.clear();
    _prefixTokens.clear();
    tokenize(fixClosingBrackets(expression));
    shuntingYard();
}
Beispiel #2
0
/* returns 0.                               */
float eval(float x, float y, int& errval) {
	stack<float> values; // Stack of values to be evaluated
	float operands[2]; // Array to contain the two operands (assuming n=2 arguments for any operator)
	
	string s_vars[2]={ftos(x), ftos(y)}; // Store x and y in one array for easy iteration
	
	for(int thisvar=0; thisvar<2; thisvar++) // Substitute for each variable
	{
		vector<string> vec_var=shuntingYard(s_vars[thisvar]);
	
		cout << "Substituting variable... " << vtos(vec_var) << endl;
		// Go through vector, inserting 'x' or 'y' into all instances of variable
		for(int i=0; i<expression.size(); i++) {
			if(expression[i]==rel_var[thisvar]) {
				expression.erase(expression.begin()+i);
				expression.insert(expression.begin()+i, vec_var.begin(), vec_var.end());
				i+=vec_var.size();
			}
		}
	}
	
	cout << "After substitution: " << vtos(expression) << endl; // Debugging stuff, displays result

	cout << "Parsing tokens..." << endl;
	for(int i=0; i<expression.size(); i++) {
		string token=expression[i];
		
		// If it's a number, push it to the stack
		if(isdigit(token[0]))
			values.push(atof(token.c_str()));
		// If it's an operator, evaluate
		else if(searchFor(token, operators, NUM_OPS)) {
			float result;
			
			if(values.size()<2) { // Not enough values
				errval=INSUFF;
				return 0.0;
			}
			
			operands[1]=values.top();
			values.pop();
			operands[0]=values.top();
			values.pop();
			
			// Evaluate the operator
			switch(token[0]) {
				case '.':
					result=operands[0]+operands[1]/pow(10, numDigits(operands[1]));
					cout << operands[1] << endl;
					break;
				case '^':
					if(operands[0]<0) {
						errval=IMAGINARY;
						return 0.0;
					}
					result=pow(operands[0], operands[1]);
					break;
				case '*':
					result=operands[0]*operands[1];
					break;
				case '/':
					if(operands[1]==0) {
						errval=DIVZERO;
						return 0.0;
					}
					result=operands[0]/operands[1];
					break;
				case '+':
					result=operands[0]+operands[1];
					break;
				case '-':
					result=operands[0]-operands[1];
					break;
				default:
					errval=OPER;
					return 0.0;
			}
			
			values.push(result);
		}
		else {
			errval=OPER;
			return 0.0;
		}
	}
	
	if(values.size()==1) { // That one value is the result
		errval=NONE;
		return values.top();
	}
	else { // Problem, too many values on stack
		errval=VAL;
		return 0.0;
	}
}
ExpressionParser::ExpressionParser(const std::string & expression)
{
    tokenize(fixClosingBrackets(expression));
    shuntingYard();
}