I am doing the exercises in Stroustrup's book, Programming: Principles and Practice Using C++. The 6th chapter uses a simple calculator to demonstrate Tokens and grammars. I realize that there are many calculator questions in the forum, but each seems to deal with a different issue. I did not find one that dealt with mine. An exercise is to add factorial capability to the calculator. That would involve altering the grammar and the tokens.
I added the exclamation point (!) to the token stream so that it would be recognized as a valid token as follows:
double primary()
{
Token t = ts.get();
switch (t.kind) {
case'(': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected");
return d;
}
case'{': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != '}') error("'}' expected");
return d;
}
case'!': // handle '!' expression
{
double d = expression();
t = ts.get();
return d;
}
case'8': // we use '8' to represent a number
return t.value; // return the number's value
default:
error("primary expected");
}
}
However, when I try to compute a factorial, I receive the 'Error: Primary expected' message. This means to me that the case of ! is not being recognized so the default (error) is being executed.
Has anyone completed this exercise? Can you show me how to add the factorial case to this calculator? Thanks very much.