开发者

How to create a function from user input?

开发者 https://www.devze.com 2023-03-25 09:23 出处:网络
So i need to use two arrays in my program. A is an array of datapoints (values x takes). and B is an开发者_Python百科 array of functions of x.

So i need to use two arrays in my program. A is an array of datapoints (values x takes). and B is an开发者_Python百科 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?


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.


Your best bet is to use a function parser library, such as FunctionParser. Other options include using a scripting language, such as Lua or Squirrel, and using a separate command line calculator application.

Parsing is a large and exciting field in its own, but writing your own parser would likely take longer than it is worth, unless you are doing this project specifically to become familiar with the subject.

0

精彩评论

暂无评论...
验证码 换一张
取 消