Parser and Calculator


You too can build a parser / calculator combination.  Take string expressions like:

     (  ( 5 / 12 ) * ( 3 + 4 - 10 ) ) / ( 1 / ( 6 * 7 + 3 ) )

parse the expression into useful structures and have a calculator generate the results.

The Parser:

Really simple: just push the operators and operands onto two stacks.  These stacks will be used by the calculator to get the results.  For the expression above, :

Operand Operator
   
  (
  (
  /
  )
  *
  (
  +
  -
  )
5 )
12 /
3 (
4 /
10 (
1 *
6 +
7 )
3 )

But Doug, all you did was list the operators and operands in order!  See how easy it is being a programmer.  You can write this parser in a couple of hours - with fairly good error handling.  I recommend treating both operators and operands as tokens and storing them in token structures.  These structures can be expanded to meet your needs - for example, I like to store the position within the string of each token for better error-handling.  Always use a token-type and use a union to store disparate types of info (assuming you code in C).

Now the tough parts - the calculator...,    error-handling...,     extending the parser...