It always returns false because your logic is reversed. You are using the || with checks == npos . If there is no one digit in the line, == npos is evaluated to true and || so you return false . You need to use the checks != npos , and then return true if any check evaluates to 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 simpler solution is to use find_first_of() instead of find() :
bool Person::contains_number(const std::string &c) { return (c.find_first_of("0123456789") != std::string::npos); }
Remy Lebeau
source share