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.

ForceMagic
  • 6,230
  • 12
  • 66
  • 88
  • accept it as string and use features from `std::regex` in `` header. provided you have c++11 compatibility – Koushik Shetty May 24 '13 at 05:09
  • 2
    You have to write a parser. Here's how you'd write one in Python using PLY http://www.dabeaz.com/ply/ply.html – Patashu May 24 '13 at 05: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 – Patashu May 24 '13 at 05:10
  • @Patashu touche. agreed. – Koushik Shetty May 24 '13 at 05:11
  • @Koushik I know from personal experience, I've tried to write one like that, and I was never convinced it was bug free, because it didn't describe a grammar, it just probably worked as far as anyone could tell ;) – Patashu May 24 '13 at 05:14
  • @Patashu oh yes i agree. but writing from scratch is not much fun either :) – Koushik Shetty May 24 '13 at 05:16
  • 1
    @Koushik Yeah, that's why there are parser generators :) – Patashu May 24 '13 at 05:16
  • Do you really mean `calculus`? or just alegbra and trignometry? It isn't the same thing. If you want to implement calculus you would be better of interfacing to something like Matlab. – user207421 May 24 '13 at 05:33

2 Answers2

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.

Community
  • 1
  • 1
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
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.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127