Reliable Software Logo

C++ In Action: Language

Exercise Solutions

  1. The only tricky operators are:
    • One’s complement. It’s a unary operator, so you should only pop one argument from the stack.
    • Left and right shifts. These are two-character operators so, after detecting a less-than or a greater-than sign, make sure the next character in the input buffer is the same as the first one. You may simply use the first character as a token.
  2. Add a Boolean data member to Calculator:
    bool _isHex;
    (Remember to initialize it in the constructor.) In the Execute method, check for token ‘x’ and toggle the flag:
    else if (token == 'x')
    {
        // toggle hex display
        _isHex = !_isHex;
        status = true;
    }
    
    In main, check this flag before displaying the contents of the stack:
    if (TheCalculator.IsHex ())
        std::cout << std::hex;
    else 
        std::cout << std::dec;
  3. Wherever values are stored or used in calculations, change the type int to bool. In particular, rewrite IStack (call it BStack) to store bool values. Here’s the relevant fragment of Calculator::Execute:
    bool b2 = _stack.Pop ();
    if (token == '!')
    {
        _stack.Push (!b2);
        status = true;
    }
    else
    {
        bool b1;
        // Special case, when only one number on the stack:
        // use this number for both operands.
        if (_stack.IsEmpty ())
            b1 = b2;
        else
            b1 = _stack.Pop ();
    
        _stack.Push (Calculate (b1, b2, token));
        status = true;
    }
    This is the Calculate method:
    bool Calculator::Calculate (bool b1, bool b2, int token) const
    { 
        bool result;
        if (token == '&') 
            result = b1 && b2; 
        else if (token == '|') 
            result = b1 || b2; 
        return result; 
    }