Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to mathematical evaluation [closed]

Tags:

Okay, so what I want to do is to use a string as input (for instance "16*12+25"), convert it to a mathematical evaluation that the computer can comprehend and return the evaluated value. I could probably write this myself, but it would most likely take quite a while and in the end, it still wouldn't end up as good as I'd like it to unless I want to put even more time into it.

So my question is, is there any script, library or api that you know can do this for C++? I have found some for both java, python and .NET. But I am not working with any of these languages and I would like to remain within C++ for as long (hopefully throughout the entire project) as possible. Do you have any good ideas or links?

like image 508
Anton Avatar asked Feb 24 '12 23:02

Anton


People also ask

How do you turn a string into an expression?

One option is to create and call new Function : var strExpr = "var1 == null && var2 != 5"; if (new Function("return " + strExpr)()) { // ... }


2 Answers

I found what I was looking for! The downloadable source is C++ and a CodeBlocks project. You can find it here: http://www.speqmath.com/tutorials/expression_parser_cpp/index.html

A far more sophisticated expression parser recommended by Jared: http://www.partow.net/programming/exprtk/index.html

like image 146
Anton Avatar answered Oct 27 '22 15:10

Anton


There is nothing built into C++ for this; all the expression parsing code belongs in the compiler. You will need to use some external library. A quick Google search brings up muParser which looks pretty reasonable.

like image 37
spencercw Avatar answered Oct 27 '22 16:10

spencercw