Search code examples
c++parsingequations

C++ Parsing equations provided by the user


I am making a program in C++ that performs some basic calculus functions. In order to create an equation to perform these functions with I am using the following code:

float equationone(float x)
{
    return  sqrt(x);
}

float equationtwo(float x)
{
    return (x * x);
}

I am wondering how can I adapt my code so the user can enter something like sqrt(x) or (x*x) and have the functions return the proper answer.


Solution

  • Not a so trivial task, because you soon would like to have parentheses, operator precedences and so on. You need to create a parser. If you want to learn how to create one from scratch, try to look for antlr. You basically delegate a tool to create a code that is far from easy to be craft manually. Of course you need to learn how to write a grammar definition, but it probably will pay in the future. If instead you need to serve a real customer in a small time with a scripting language, consider looking on something else than c++. Have a look at this other reply on Stackoverflow.