Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm working on a project in c++ (which I just started learning) and can't understand why this function is not working. I'm attempting to write a "Person" class with a variable first_name, and use a function set_first_name to set the name. Set_first_name needs to call a function(the one below) to check if the name has any numbers in it. The function always returns false, and I'm wondering why? Also, is this the best way to check for numbers, or is there a better way?

   bool Person::contains_number(std::string c){ // checks if a string contains a 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 it contains number

        return false;
        }
        return true;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

Change all your || to &&.

Better yet:

return std::find_if(s.begin(), s.end(), ::isdigit) != s.end();        

Or, if you have it:

return std::any_of(s.begin(), s.end(), ::isdigit);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...