Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function from user input?

So i need to use two arrays in my program. A is an array of datapoints (values x takes). and B is an array of functions of x. Both are to be entered by the user(from the keyboard).

My problem is in reading in the elements of B. For example, A={1,2,3} and B={sin(x), x+5} where x is supposed to take in all values of A. I am relatively new to c++ and am not sure of the best way to do this. I read somewhere about Parsing but it seemed a bit complicated. Can it be done without parsing?

like image 672
aa15 Avatar asked Dec 11 '25 15:12

aa15


1 Answers

No, this is complicated. C++ is a statically-typed and non-reflective language: you cannot create actual C++ code at runtime.

The next-best thing to do is to write a small parser that matches the input against a list of recognized functions that you choose to provide. It's not that hard to do, but you'll need to write some code.

Boost contains some libraries to help you with this (Spirit), I believe, but it's also not terribly difficult to do by hand. You just need to lex the input into tokens and build up a parse tree.

like image 146
Kerrek SB Avatar answered Dec 14 '25 11:12

Kerrek SB