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
|
#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <cctype>
struct player
{
std::string name_ ;
// https://en.cppreference.com/w/cpp/container/array
static constexpr std::size_t NUM_SCORES = 3 ;
std::array< int, NUM_SCORES > scores_ ;
const std::string& name() const { return name_ ; }
const std::array< int, NUM_SCORES >& scores() const { return scores_ ; }
void print() const
{
std::cout << "name: " << name() << " scores: [ " ;
// range based loop: http://www.stroustrup.com/C++11FAQ.html#for
for( int s : scores() ) std::cout << s << ' ' ;
std::cout << "]\n" ;
}
// return true if there is a match for the player's name (ignoring case)
bool has_name( const std::string& required_name ) const
{
if( name().size() != required_name.size() ) return false ;
// check char by char, ignoring case; return false on mismatch
for( std::size_t i = 0 ; i < name().size() ; ++i )
{
// https://en.cppreference.com/w/cpp/string/byte/toupper
const unsigned char a = name()[i] ;
const unsigned char b = required_name[i] ;
if( std::toupper(a) != std::toupper(b) ) return false ;
}
return true ;
}
};
// search for a player by name, print the scores of the player
bool print_scores_of( const std::vector<player>& players, const std::string& player_name )
{
for( const player& p : players ) // for each player in the vector
{
if( p.has_name(player_name) ) // if there is a match for the name
{
p.print() ;
return true ;
}
}
std::cout << "there is no player with name '" << player_name << "'\n" ;
return false ;
}
int main()
{
const std::vector<player> players { { "abcd", {{1,2,3}} }, { "efgh", {{4,5,6}} }, { "ijkl", {{7,8,9}} } } ;
std::string name ;
while( std::cin >> name )
{
std::cout << "\nsearching for name '" << name << "'\n" ;
print_scores_of( players, name ) ;
}
}
| |