I am attempting to write a program that evaluates a mathematical expression after parsing it. I have the parser correct, using a string to strip it into tokens and compare it to grammar rules to validate the expression. It should be able to evaluate expressions of type
(3+2)*4+-1= where negative numbers are included. I am having a tough time with the evaluation part.

string result;
string token1;
string token2;
double c=0;
double d=0;
stack<double> nums;

for(int i=0; i<exp.size();i++)
{
	token1= exp.at(i);
	if(isdigit(exp.at(i)))
	{ c= atof (token1.c_str());
	   nums.push(c);		
	}
	switch(s_mapStringValues[token1])			//
	{
	       case PLUS:
			break;
	       case MINUS:
			break;
	       case MUL:
			break;
	       case DIV:
			break;
	}

		
		
	}

Using the idea of pushing the number onto a stack and then popping last two and evaluating when finding an operator does not work when I have two operators following each other as 3*-4. Any ideas around this?

3*-4. Any ideas around this?

In the evaluation of polynomial expressions, it is safe to treat all " - " minus signs as preceding negative numbers (it is safe to assume there is no subtraction). The only special case one must consider is the case of the double negative, wich can be easily tested for.

Example:

-3x^2-4x = -5

Can trasnlate to:

Negative Three x squared plus negative four x = negative 5

Notice that there is no "subraction" involved with the evaluation of polynomials. With the exception of the double negative, you can safely assume all minus signs are only to identify negative values.

If your program supports only the basic math operations (addition, subraction, multiplication and division) between your polynomial terms, then all you really have to identify is * multiplication and / division... everything else is addition.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.