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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <iostream>
#include <string> // for std::string
#include <algorithm> // for std::transform
#include <cctype> // for std::tolower
const std::string flavors[] =
{
"Chocolate",
"Vanilla",
"Gumball",
"Turkey",
"Wild Nuts"
};
const std::string sizes[] =
{
"Small",
"Medium",
"Large",
"Super Gigantic"
};
// a common method of getting the number of elements in an array (in
// the scope in which the array is defined) is to take the overall
// size of the array and divide it by the size of one of it's elements.
const unsigned num_flavors = sizeof(flavors) / sizeof(flavors[0]) ;
const unsigned num_sizes = sizeof(sizes) / sizeof(sizes[0]) ;
// just to shorten things up a bit for posting:
typedef const std::string const_string ;
// returns true if to_check occurs in labels.
bool check_against( const_string to_check, const_string labels[], unsigned elements ) ;
// convenience function for displaying the list of flavors/sizes
void display(std::ostream & out, const_string labels[], unsigned elements,
const_string title, const_string prompt) ;
int main()
{
std::string flavor ;
do
{
display( std::cout, flavors, num_flavors,
"Flavors are:", "What flavor would you like?" ) ;
std::getline(std::cin, flavor);
} while (!check_against(flavor, flavors, num_flavors)) ;
std::string size ;
do
{
display( std::cout, sizes, num_sizes,
"Sizes are:", "What size would you like?") ;
std::getline(std::cin, size) ;
} while ( !check_against(size, sizes, num_sizes) ) ;
std::cout << "You ordered a " << size << ' ' << flavor << " icecream.\n" ;
}
// another convenience function: returns a lower cases version
// of the string supplied.
std::string lower_case( const_string s )
{
std::string t = s ;
std::transform(t.begin(), t.end(), t.begin(), std::tolower) ;
return t ;
}
bool check_against( const_string to_check, const_string labels[], unsigned elements )
{
std::string check_me = lower_case(to_check) ;
for ( unsigned i=0; i<elements; ++i )
{
if ( check_me == lower_case(labels[i]) )
return true ;
}
return false ;
}
void display(std::ostream & out, const_string labels[], unsigned num_labels,
const_string title, const_string prompt )
{
out << '\n' << title << '\n' ;
for ( unsigned i=0; i<num_labels; ++i )
out << '\t' << labels[i] << '\n' ;
out << prompt << '\n' ;
}
|