The Craft Of Coding

CPP 4-Apr Implementing Designs Incrementally

Posted by Pete Mon, 04 Apr 2016 01:54:00 GMT

Using a vector of strings, the sequence of strings you expect to see is something like

     ( // optional, might not be there
     1 // any double
     + // only supporting addition
     1 // any double
     ) // optional, but must be there if opening bracket was

Ignoring brackets for now, sequence we will see will be 1 + 1

So to start out, expect to see an number, so need to convert that string to a float.

     #include <sstream>
     //in some function
     double value;
     istringstream iss(strNum);
     iss >> value;
     // now value has the double value or 0.0

Put this value into an Expression * pLeft (or your equivalent class) the one you would use if the only input were 1

now read the next item from the vector - it should be an operator, so make the appropriate Addition subclass, and set it as the operator for a new Expression * pTemp

The first number you read now in pLeft can now be set as the LHS of pTemp

The next thing you read will be a number (since we are ignoring brackets for now), so convert this string to a number and set it as the RHS of pTemp. So now pTemp has a LHS, Addition and RHS - a complete expression, made up of three expressions, two that are just numbers, one that is addition with a LHS and RHS.

To make it possible to loop around for the rest of the vector (1 + 2 + 3…), all you need to do now is set pLeft = pTemp, and then you are back to expecting an operator from the vector, or the end of the vector.

At the end of the vector, pLeft contains the full expression that you are interested in.

© 2016 Pete McBreen it is well known that a vital ingredient of success is not knowing that what you’re attempting can’t be done. — Terry Pratchett (Equal Rites)