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
|
#include <iostream>
#include <string>
#include <cctype>
// return true if the two strings are the same, ignoring case
bool eq_ncase( const std::string& a, const std::string& b )
{
if( a.size() != b.size() ) return false ;
for( std::size_t i = 0 ; i < a.size() ; ++i )
if( std::toupper( a[i] ) != std::toupper( b[i] ) ) return false ;
// pedantic: std::toupper( (unsigned char)a[i] ) etc.
return true ;
}
// look up name, return phone number (return empty string if not found)
std::string lookup_by_name( const std::string& target_name, const std::string names[],
const std::string phone_numbers[], std::size_t num_entries )
{
for( std::size_t i = 0 ; i < num_entries ; ++i )
if( eq_ncase( target_name, names[i] ) ) return phone_numbers[i] ;
return {} ; // not found: return empty string
}
int main()
{
const int N = 7 ;
const std::string dwarves[N] = { "Doc", "Grumpy", "Happy", "Sleepy", "Dopey", "Bashful", "Sneezy" };
const std::string numbers[N] = { "111", "222222", "33333", "444444", "55555", "6666666", "777777" };
std::string target_name ;
while( std::cout << "enter the name to look up: " && std::cin >> target_name )
{
const std::string number = lookup_by_name( target_name, dwarves, numbers, N ) ;
if( !number.empty() ) std::cout << "phone number: " << number << '\n' ;
else std::cout << "lookup failed\n" ;
}
}
|