0

In Python I have such an opportunity, to write string named s with something and then execute the code inside this string with exec() function:

s = input()   # Something like 5*x**2-6
exec('def f(x):\n    return ' + s)
print(f(5))

How can I do something like that in C++? In my program user is supposed to input some function, line segment and get the x from this segment, for which f(x) = 0. I got everything done, but the function f(x) for which equation is solved can only be changed in the source code, which is of course not very suitable.

Thanks in advance!

Botje
  • 26,269
  • 3
  • 31
  • 41
Bonderson
  • 13
  • 2
  • What you are asking is fundamentally impossible in C++. Code needs to be compiled up front, while Python is an interpreted language. Now, if your problem is "how do I evaluate a string containing a mathematical expression", that is something else entirely. – Botje Oct 01 '20 at 12:09
  • You have to write some eval function that does the evaluation of the math expression. Or find some library that does it for you. – drescherjm Oct 01 '20 at 12:09
  • 1
    Does this answer your question? [How to evaluate any given expression](https://stackoverflow.com/questions/10642959/how-to-evaluate-any-given-expression) – Botje Oct 01 '20 at 12:10
  • Are you supposed to write a full C++ compiler? What kind of assignment is this? – JHBonarius Oct 01 '20 at 12:56

2 Answers2

1

Keep the input as a string, then use the string::replace method to substitute the x with a number, then evaluate the expression as this person did: Evaluating arithmetic expressions from string in C++

I think this could work.

  • 1
    Good find! Of course if you're already tokenizing the expression it is easy to map non-number atoms to a variable in a `std::map`. – Botje Oct 01 '20 at 12:22
-1

Define your function elsewhere : int f(num){... return x}(where x has to be int, since we defined the function as integer) , after you get the input print out f(input). Learn more about C++ functions here

Dushan
  • 1
  • 1