I'm doing the exercises in Stroustrup's new book "Programming Principles and Practice Using C++" 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?
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.
char ch;
cin >> ch; // note that >> 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 >> val; // read a floating-point number
return Token('8',val); // let '8' represent "a number"
}
case 's':
{
char q, r, t, br;
cin >> q >> r >> t >> br;
if (q == 'q' && r == 'r' && t == 't' && br == '(') {
cin.putback('('); // put back the bracket
return Token('s'); // let 's' represent sqrt
}
}
default:
error("Bad token");
}