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

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

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

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

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

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...