Source of two_flags.cpp


  1: //two_flags.cpp
  2: //Tests whether either of two conditions is satisfied. Illustrates a 
  3: //loop controlled by two flags (two conditions). Note that when such
  4: //a loop ends it may be because either (or perhaps both) of the two 
  5: //conditions failed.

  7: #include <iostream>
  8: using namespace std;

 10: int main()
 11: {
 12:     cout << "\nThis program tries to get the user to enter an integer "
 13:         "from 1 to 3.\nHowever, only three tries are permitted before "
 14:         "the program gives up and quits.\n\n";

 16:     bool validEntry = false; //Since there are no entries yet
 17:     bool outOfTries = false; //Since no tries have been made yet

 19:     int i;
 20:     int tryCount = 0;

 22:     while (!validEntry && !outOfTries)
 23:     {
 24:         cout << "Enter an integer in the range 1..3: ";
 25:         cin >> i;
 26:         cout << endl;
 27:         tryCount++;
 28:         validEntry = (i >= 1  &&  i <= 3);
 29:         outOfTries = (tryCount == 3);
 30:         if (!validEntry && !outOfTries)
 31:             cout << "Invalid entry. Try again.\n";
 32:     }

 34:     if (validEntry)
 35:         cout << "The valid entry "      << i
 36:              << " was entered on try #" << tryCount << ".\n";
 37:     else if (outOfTries)
 38:         cout << "You ran out of tries!\n";
 39:     cout << endl;
 40: }