Saturday, 17 September 2016

Chapter 6 // Exercise 2 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 6 // Exercise 2

Add the ability to use {} as well as () in the program, so that {(4+5)*6}/(3+4) will be a valid expression.

(Since the code is so long, I'm only posting the functions I made changes to as most of it remains unchanged from the drill. I also highlighted the bits I added/changed)

Token Token_stream::get()
{
if (full)
{       // do we already have a Token ready?
// remove token from buffer
Token_stream::full = false;
return buffer;
}


char ch;
cin >> ch;    // note that >> skips whitespace (space, newline, tab, etc.)

switch (ch)
{
case '=':    // for "print"
case 'x':    // for "quit"


case '(': 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
cin >> val;              // read a floating-point number
return Token('#', val);   // let '#' represent "a number"
}

default:
error("Bad token");
}
}

//------------------------------------------------------------------

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;
break;
}

case '(':    // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected)");
return d;
break;
}

case '#':            // we use '#' to represent a number
{
return t.value;  // return the number's value
break;
}

default:
error("primary expected");
}

}


No gonna lie, I cried a little bit on the inside when I saw this question, mainly because I have trouble understanding exactly how Token works. I wish he'd gone through every bit of the code with us and explained it but alas, that is too much to ask.

After I finished procrastinating, I realised it was actually ridiculously easy. I added two cases to get() to handle with '{' and '}'. Then I copied the case for '(' in primary() and modified it to work with '{'. I put these first because obviously they have priority over '()'.



No comments:

Post a Comment