C++ IsFloat function

前端 未结 18 1312
不思量自难忘°
不思量自难忘° 2020-12-09 15:58

Does anybody know of a convenient means of determining if a string value \"qualifies\" as a floating-point number?

bool IsFloat( string MyString )
{
   ... e         


        
18条回答
  •  星月不相逢
    2020-12-09 16:47

    I always liked strtof since it lets you specify an end pointer.

    bool isFloat(const std::string& str)
    {
        char* ptr;
        strtof(str.c_str(), &ptr);
        return (*ptr) == '\0';
    }
    

    This works because the end pointer points to the character where the parse started to fail, therefore if it points to a nul-terminator, then the whole string was parsed as a float.

    I'm surprised no one mentioned this method in the 10 years this question has been around, I suppose because it is more of a C-Style way of doing it. However, it is still perfectly valid in C++, and more elegant than any stream solutions. Also, it works with "+inf" "-inf" and so on, and ignores leading whitespace.

    EDIT

    Don't be caught out by empty strings, otherwise the end pointer will be on the nul-termination (and therefore return true). The above code should be:

    bool isFloat(const std::string& str)
    {
        if (str.empty())
            return false;
    
        char* ptr;
        strtof(str.c_str(), &ptr);
        return (*ptr) == '\0';
    }
    

提交回复
热议问题