-1

my question is the following: supposing I have a program, written in C++, which takes a function and gives its integral. In this program I write the function manually, in the source code, and I change its signature every time I want to integrate another function. If now I want to initialize this function in input (for example giving a string), in order to directly initialize it at compiling time, how could I do?

I would be interested in having something like this:

$ ./program
$ Give me the function name: x+3y+4

and now the function is initialized with:

int func() { return x+3y+4; }
Gianluca Bianco
  • 656
  • 2
  • 11
  • 4
    https://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-from-string-in-c – πάντα ῥεῖ Jan 12 '22 at 17:13
  • Unfortunately there's no equivalent for javascripts `eval()` function in standard c++, it's probably more complicated than you imagine. – πάντα ῥεῖ Jan 12 '22 at 17:22
  • You're looking at writing a minimal language interpreter. For example BASIC or Matlab. Not a simple task. – Thomas Matthews Jan 12 '22 at 17:23
  • @ThomasMatthews well, there are some APIs like lua, or tcl – πάντα ῥεῖ Jan 12 '22 at 17:28
  • 1
    Code generation and a build automation tool. Write a little program that asks for and reads in the formula and generates a source file that will be compiled and linked in. The build automation tool always runs the little program to generate the integrator and then builds the final program. – user4581301 Jan 12 '22 at 17:47

1 Answers1

1

You need this: https://github.com/ArashPartow/exprtk

It is only slightly slower than compiling the expression in native code.

There are also others, you can see most of them here: https://github.com/ArashPartow/math-parser-benchmark-project

(Disclaimer: I am the author of the Node.js bindings: https://github.com/mmomtchev/exprtk.js)

mmomtchev
  • 2,497
  • 1
  • 8
  • 23