Adding the ! operator and sqrt(), pow() etc. to a calculator example application
<p>I'm doing the exercises in Stroustrup's new book <a href="http://www.stroustrup.com/Programming/" rel="nofollow">"Programming Principles and Practice Using C++"</a> and was wondering if anyone on SO has done them and is willing to share the knowledge? Specifically about the calculator that's developed in Chap 6 and 7. Eg the questions about adding the ! operator and sqrt(), pow() etc. I have done these but I don't know if the solution I have is the "good" way of doing things, and there are no published solutions on Bjarne's website. I'd like to know if I am going down the right track. Maybe we can make a wiki for the exercises?</p>

<p>Basically I have a token parser. It reads a char at a time from cin. It's meant to tokenise expressions like 5*3+1 and it works great for that. One of the exercises is to add a sqrt() function. So I modified the tokenising code to detect "sqrt(" and then return a Token object representing sqrt. In this case I use the char 's'. Is this how others would do it? What if I need to implement sin()? The case statement would get messy. </p>

<pre><code>char ch;
cin &gt;&gt; ch;    // note that &gt;&gt; skips whitespace (space, newline, tab, etc.)

switch (ch) {
 case ';':    // for "print"
 case 'q':    // for "quit"
 case '(': 
 case ')': 
 case '+': 
 case '-': 
 case '*': 
 case '/': 
 case '!':
  return Token(ch);        // let each character represent itself
 case '.':
 case '0': case '1': case '2': case '3': case '4':
 case '5': case '6': case '7': case '8': case '9':
  {    
   cin.putback(ch);         // put digit back into the input stream
   double val;
   cin &gt;&gt; val;              // read a floating-point number
   return Token('8',val);   // let '8' represent "a number"
  }
 case 's': 
  {
   char q, r, t, br;
   cin &gt;&gt; q &gt;&gt; r &gt;&gt; t &gt;&gt; br;
   if (q == 'q' &amp;&amp; r == 'r' &amp;&amp; t == 't' &amp;&amp; br == '(') {
    cin.putback('('); // put back the bracket
    return Token('s'); // let 's' represent sqrt
   }

  }

 default:
  error("Bad token");
}
</code></pre>
