Math expression evaluator

Jun 22, 2012 at 5:18pm
While debugging in Visual C++, I really like the watch windows. Whenever I enter a variable or an expression on the left side, it shows its value on the right side. I want to put such a feature in my program. I want to take an expression from the user and evaluate it. I need something which can evaluate a mathematical expression and return the answer which I will use later in my program.

I tried making a program which takes input from the user into a string. Then I check for operators, brackets, numbers, variables, etc. and evaluate the mathematical expression. It usually works fine but sometimes it gives a wrong answer or sometimes it just terminates unexpectedly. I also tried making a derivative calculator the same way, but that too gives errors (as it is based on the former program). I'm not able to find the bug in my program, and its source code is huge.

If anyone knows about such a free program or a library, please tell me about it. If such a program doesn't exist, I'll continue working on my own program. But I don't want to spend time on making a program which is both hard to make and already exists (maybe).

Some people also told me that a C++ interpreter (if such a thing exists) can help me.
Last edited on Jun 22, 2012 at 5:19pm
Jun 23, 2012 at 6:07am
At a very low level, there are lex and yacc. What you are encountering is a common set of parsing problems like matching parens, brackets, and various operators. All compilers must do this and hence, my reference to lex and yacc. If these are overkill for you, the you are left writing a parser. This is non-trivial, but I've done it and I'm not a superstar. Basically, a push-pop model (pushing a block until you run into a paren and recursively) and then identifying the sequence of operators in a sequence is what you need to do. You also need a way to identify numbers, variables, and sequences. Once you have that working for a simple equation, the do it recursively with parens and you should be good to go. It's a lot of code tho.

Link:
http://dinosaur.compilertools.net/
Jun 23, 2012 at 8:26am
Hint: search for the closing parentheses (then find the opening to go with it)!
Last edited on Jun 23, 2012 at 8:26am
Jun 23, 2012 at 4:59pm
I don't have a problem with parentheses or detecting numbers or operators. There is something else which I don't know what. The problem starts only when I work with variables and math functions. Lex and yacc are difficult to work with.
Jul 7, 2012 at 7:53am
I made my own program with help from some books from the library. It's working fine.
Topic archived. No new replies allowed.