1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include <algorithm>
#include <cctype>
#include <functional>
#include <iostream>
using namespace std;
// This is our list of colors.
const char* VALID_COLORS[] =
{
"black",
"brown"
};
// These are indices into our list of colors.
// Notice how the LAST index indicates an invalid color
typedef enum
{
color_black,
color_brown,
color_invalid
}
valid_color_t;
// This function transforms a color name into a valid_color_t
//
valid_color_t is_color_valid( string color )
{
// Transform string to lowercase for comparisons
transform( color.begin(), color.end(), color.begin(), ptr_fun <int, int> ( tolower ) );
// Locate the
return static_cast <valid_color_t> (
find( VALID_COLORS, VALID_COLORS + color_invalid, color ) - VALID_COLORS
);
}
int main()
{
// This is the result of our Input And Validate operation
valid_color_t validated_color;
// The block that follows here is the Input And Validate operation
// First, tell the user what we want
cout << "Please enter a color (black or brown): " << flush;
while (true)
{
// Get the user's response
string s;
getline( cin, s );
// Validate the user's response
validated_color = is_color_valid( s );
// If the user's response passed our validation, we are done
if (validated_color != color_invalid) break;
// Otherwise, give the user a little more explicit instruction and try again
cout << "Please enter either BLACK or BROWN: " << flush;
}
// Now that we have a validated color from the user, we can use it
cout << "Good job! You entered " << VALID_COLORS[ validated_color ] << "!\n";
return 0;
}
|