7

I'm looking for an flexible but also considerably fast way to do simple value conversion and calculations at the basis of descriptive calculator strings.

For example something like this:

double r = 1.0;
double d = mathf( "sin(%1)+2*%2", r, M_PI );
double e = mathf( "%1 / 180.0 * %2", r, M_PI );

The important think is the mathematical operations can be evaluated at runtime and loaded from config file. I was even considering some sort of scripting language integration but it seems that doesn't come in sleek and fast?

Any ideas if something like mathf exists for C++?

alexrider
  • 4,449
  • 1
  • 17
  • 27
Hhut
  • 1,128
  • 1
  • 12
  • 24
  • 2
    When you look at the internals of a `printf()` implementation, you will realize that there is nothing "sleek and fast" about it. Parsing a format string, with all the options that get added over time, plus the potential of false input and how to react on it in a meaningful (i.e., non-crashing) way... – DevSolar Apr 22 '13 at 13:05
  • sleek and fast? think about how your compiler processes arithmetic expressions... – krsteeve Apr 22 '13 at 13:19
  • I meant "sleek and fast" in comparison to add full scale python integration for these small operation. – Hhut Apr 22 '13 at 13:37

1 Answers1

5

Try searching around a little more. This is a pretty common thing. It's parsing, and every compiler does it. Makes this a bit like parsception.

Solve equation from string to result in C

Evaluate a simple string mathmatical expression

Convert string to mathematical evaluation

etc etc.

There's two ways to go about it, one is write your own, the second is find a library which seems like what you're looking for. I don't know of anything like that in the C++ standard libs, in ruby and a bunch of other languages for sure, you can just eval the string, but in C++ you're probably going to have to borrow a library from the web or something. Try that last link, it looked promising for that.

Community
  • 1
  • 1
NathanTempelman
  • 1,301
  • 9
  • 34
  • 16
    Thanks... I didn't think of separating the printf and evaluation part... that indeed makes it a lot simpler. The following looks good and it should work: http://www.partow.net/programming/exprtk/index.html – Hhut Apr 22 '13 at 13:43