c++ - Function to check if string contains a number -


i'm working on project in c++ (which started learning) , can't understand why function not working. i'm attempting write "person" class variable first_name, , use function set_first_name set name. set_first_name needs call function(the 1 below) check if name has numbers in it. function returns false, , i'm wondering why? also, best way check numbers, or there better way?

   bool person::contains_number(std::string c){ // checks if string contains number         if (c.find('0') == std::string::npos || c.find('1') == std::string::npos || c.find('2') == std::string::npos || c.find('3') == std::string::npos         || c.find('4') == std::string::npos || c.find('5') == std::string::npos || c.find('6') == std::string::npos || c.find('7') == std::string::npos         || c.find('8') == std::string::npos || c.find('9') == std::string::npos){// checks if contains number          return false;         }         return true;     } 

it returns false because logic backwards. using || operator == npos checks. if 1 particular digit missing string, == npos evaluates true , || satisfied, return false. need using != npos checks , return true if check evaluates true:

bool person::contains_number(const std::string &c) {     if (c.find('0') != std::string::npos ||         c.find('1') != std::string::npos ||         c.find('2') != std::string::npos ||         c.find('3') != std::string::npos ||         c.find('4') != std::string::npos ||         c.find('5') != std::string::npos ||         c.find('6') != std::string::npos ||         c.find('7') != std::string::npos ||         c.find('8') != std::string::npos ||         c.find('9') != std::string::npos)     {         return true;     }      return false; } 

or:

bool person::contains_number(const std::string &c) {     return (         c.find('0') != std::string::npos ||         c.find('1') != std::string::npos ||         c.find('2') != std::string::npos ||         c.find('3') != std::string::npos ||         c.find('4') != std::string::npos ||         c.find('5') != std::string::npos ||         c.find('6') != std::string::npos ||         c.find('7') != std::string::npos ||         c.find('8') != std::string::npos ||         c.find('9') != std::string::npos     ); } 

a simplier solution use find_first_of() instead of find():

bool person::contains_number(const std::string &c) {     return (c.find_first_of("0123456789") != std::string::npos); }     

Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -