3

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?

3
  • The best way is parsing, but don't worry. Go through it, it has a terrible appearance, but it's doable and not as complicated as it shows Commented Jul 31, 2011 at 12:46
  • can't understand your question. Is question "how to store functions in array?" or your B should be {{sin 1,6},{sin2,7},{sin 3,8}} Commented Jul 31, 2011 at 12:47
  • You won't get around parsing the expressions yourself and creating the needed function objects/selecting the needed function pointers. Commented Jul 31, 2011 at 12:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You could dynamically write the correct combination of 0's and 1's to a filed that would be used as a shared object and then load it in and access the new function via pointer :)
You'd still have to parse and lex the input to determine the correct combination of 0s and 1s.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.