1

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.

8
  • accept it as string and use features from std::regex in <regex> header. provided you have c++11 compatibility Commented May 24, 2013 at 5:09
  • 2
    You have to write a parser. Here's how you'd write one in Python using PLY dabeaz.com/ply/ply.html Commented May 24, 2013 at 5:09
  • @Koushik Writing a parser using regexes is incredibly difficult to get right, due to problems like precedence/unary minus/if you want to define new operators/etc Commented May 24, 2013 at 5:10
  • @Patashu touche. agreed. Commented May 24, 2013 at 5:11
  • 1
    @Koushik Yeah, that's why there are parser generators :) Commented May 24, 2013 at 5:16

2 Answers 2

2

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.

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.