Code Cookbook

Table of Contents


1. Looping

1.1. Make sure int input is valid

int GetIntInput( int minval, int maxval )
{
  // Ask the user to enter a choice between minval and maxval
  int choice;
  cout << "Enter # between " << minval << "-" << maxval << ": ";
  cin >> choice;

  // Have the user re-enter their selection while their selection is invalid
  while ( choice < minval || choice > maxval )
  {
    cout << "Invalid selection! Try again: ";
    cin >> choice;
  }

  // Input is finally valid; return it back to the caller
  return choice;
}

1.2. Basic program loop

bool running = true;
while ( running )
  {
    // Main menu
    cout << "MAIN MENU" << endl;
    cout << "0. Quit" << endl;
    cout << "1. Do thing A" << endl;
    cout << "2. Do thing B" << endl;

    // Get user's selection
    int choice = GetIntInput( 0, 2 );

    // Perform some operation based on their input
    switch( choice )
      {
      case 0:
        {
          // The loop will end and program will stop.
          running = false;
        }
        break;

      case 1:
        {
          // Do thing A
        }
        break;

      case 2:
        {
          // Do thing B
        }
        break;
      }
  }

cout << endl << "Goodbye." << endl;

1.3. Display all items in a vector

// Example vector object
vector<TYPE> my_vector;

// Display a list of each element's INDEX and VALUE.
for ( size_t i = 0; i < my_vector.size(); i++ )
{
  cout << i << ". " << my_vector[i] << endl;
}

Author: Rachel Wil Sha Singh

Created: 2023-10-31 Tue 16:41

Validate