Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

You need to write a parser to break up the string into components (numbers, operators etc) then use reverse polish to process it. The page has links on how to convert to infix notation to reverse polish notation. LEX/YACC could help you to do the parsing bit.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top