How to determine if a string is a number with C++?

后端 未结 30 1963
遇见更好的自我
遇见更好的自我 2020-11-22 08:46

I\'ve had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am r

30条回答
  •  一生所求
    2020-11-22 09:10

    This function takes care of all the possible cases:

    bool AppUtilities::checkStringIsNumber(std::string s){
        //Eliminate obvious irritants that could spoil the party
        //Handle special cases here, e.g. return true for "+", "-", "" if they are acceptable as numbers to you
        if (s == "" || s == "." || s == "+" || s == "-" || s == "+." || s == "-.") return false;
    
        //Remove leading / trailing spaces **IF** they are acceptable to you
        while (s.size() > 0 && s[0] == ' ') s = s.substr(1, s.size() - 1);
        while (s.size() > 0 && s[s.size() - 1] == ' ') s = s.substr(0, s.size() - 1);
    
    
        //Remove any leading + or - sign
        if (s[0] == '+' || s[0] == '-')
            s = s.substr(1, s.size() - 1);
    
        //Remove decimal points
        long prevLength = s.size();
    
        size_t start_pos = 0;
        while((start_pos = s.find(".", start_pos)) != std::string::npos) 
            s.replace(start_pos, 1, "");
    
        //If the string had more than 2 decimal points, return false.
        if (prevLength > s.size() + 1) return false;
    
        //Check that you are left with numbers only!!
        //Courtesy selected answer by Charles Salvia above
        std::string::const_iterator it = s.begin();
        while (it != s.end() && std::isdigit(*it)) ++it;
        return !s.empty() && it == s.end();
    
        //Tada....
    }
    

提交回复
热议问题