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 <iostream>
#include <iomanip>
#include <string>
#include <cctype>
struct TeleType
{
std::string name;
std::string phoneNo;
TeleType* next = nullptr ;
};
void print( const TeleType& tt )
{
std::cout << "name: " << std::left << std::setw(20) << tt.name
<< "phone: " << tt.phoneNo << '\n' ;
}
void print_all( const TeleType* first )
{ for( const TeleType* p = first ; p != nullptr ; p = p->next ) print(*p) ; }
// compare two strings for equality ignoring case; return true if equal
static bool cmp_equal_ignore_case( const std::string& a, const std::string& b )
{
if( a.size() != b.size() ) return false ; // strings of differing lengths are not equal
for( std::size_t i = 0 ; i < a.size() ; ++i ) // compare each character, ignoring case
if( std::tolower( a[i] ) != std::tolower( b[i] ) ) return false ; // mismatch, not equal
return true ; // all characters were matched
}
// return nullptr if TeleType with searched for name is not found
const TeleType* find_by_name( const TeleType* first, std::string name )
{
for( const TeleType* p = first ; p != nullptr ; p = p->next )
if( cmp_equal_ignore_case( p->name, name ) ) return p ; // found it
return nullptr ;
}
int main()
{
TeleType c = { "Lanfrank, John", "(555) 718-4581", nullptr };
TeleType b = { "Dolan, Edith", "(555) 682-3104", std::addressof(c) };
TeleType a = { "Acme, Sam", "(555) 898-2392", std::addressof(b) };
TeleType* first = std::addressof(a) ;
print_all(first) ;
std::string name_to_find ;
std::cout << "\nWhat name are you looking for? " ;
std::getline( std::cin, name_to_find ) ;
const auto p = find_by_name( first, name_to_find ) ;
if( p != nullptr )
{
std::cout << "found name '" << name_to_find << "' : " ;
print(*p) ;
}
else std::cout << "did not find name '" << name_to_find << "'\n" ;
}
|