Program: Binary Shifts




Code below:

// Binary Shifts - Phil Gardner

#include <iostream> // Program will be using keyboard and screen
#include <climits> // Defines max values for integers

using namespace std; // Will be using standard identifiers cin, cout, endl


int inputValidInteger( string txt )
{
    // Validates input until an integer is entered
    int i;
    bool happy = false;

    do
    {
        cout << txt << " ";
        cin >> i;

        if ( cin.good() )
            happy = true;
        else
        {
            // Throw away the whole line of invalid characters, ready for the next input
            cin.clear();
            cin.ignore( INT_MAX, '\n' );
            cout << "Not a valid integer!" << endl;
        }

    } while ( not happy );

    return i;
}

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


int main()
{
  unsigned short originalNumber, placesToShiftBy, shiftedResult;
  char direction;

  do
  {
    // Allow user to type in value, choose kind of shift and how many places to shift
    originalNumber = inputValidInteger( "Type in a positive whole number: ");

    cout << "Shift to the left or to the right? l or r: " << endl;
    cin >> direction;

    placesToShiftBy = inputValidInteger( "Shift by how many places? ");

    // Determine what to do to the value
    switch ( direction )
    {
        // Shift value to the left
        case 'l': case 'L':
        {
            shiftedResult = originalNumber << placesToShiftBy;
            cout << "After shifting, the result is " << shiftedResult << endl;
        }
        break;

        // Shift value to the right
        case 'r': case 'R':
        {
            shiftedResult = originalNumber >> placesToShiftBy;
            cout << "After shifting, the result is " << shiftedResult << endl;
        }
        break;

        // Made a bad choice - neither left nor right
        default:
            cout << "Error - must either shift left or right" << endl;
        break;
    } // end of switch statement

    cout << endl << " - - - - - - -" << endl << endl;

  } while ( true );

  return 0;
}