How to put string content into source code?

I'm trying to write a program that prompts the user to enter a math expression (i.e 2*x + x*x) and a value of x. Then generate the value of y. My real question is: Is there a way to put the content of a string into the source code?


string math_function;
double x, y;
cout << "Enter the function: ";
getline(cin, math_function);
cout << "x = ";
cin >> x;

y = [[Content of string math_function]];

cout << "y = " << y << endl;

Hunter Rowland
Is there a way to put the content of a string into the source code?

What do you mean by "put the [content of the string] into [source code]" ?

Some programming languages (usually interpretated languages) have such a feature but C/C++ can not do that.
Last edited on
You can bring in a string of course but how are you going to evaluate the expression? You'll have to parse it into tokens and write your own code to do the math properly. Remember, simply replacing the variable x with what the user inputs will usually give you a wrong answer. Look at your example for an x value of 3: 2 * 3 + 3 * 3 = 27 but that's wrong. Using the proper operator precedence it should really be: (2 * 3) + (3 * 3) = 6 + 9 = 15.

Too bad that C (has) no eval(). Says the guy who's username is cnoeval!
If we're talking about evaluating a mathematical expression, then I'd use a suitable math expresion parser library, like muParser, when writing utility or test code.

muParser - a fast math parser library

But I assume we're talking about a programming exercise here?

Last edited on
Topic archived. No new replies allowed.