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

后端 未结 30 2431
遇见更好的自我
遇见更好的自我 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:11

    A solution based on a comment by kbjorklu is:

    bool isNumber(const std::string& s)
    {
       return !s.empty() && s.find_first_not_of("-.0123456789") == std::string::npos;
    }
    

    As with David Rector's answer it is not robust to strings with multiple dots or minus signs, but you can remove those characters to just check for integers.


    However, I am partial to a solution, based on Ben Voigt's solution, using strtod in cstdlib to look decimal values, scientific/engineering notation, hexidecimal notation (C++11), or even INF/INFINITY/NAN (C++11) is:

    bool isNumberC(const std::string& s)
    {
        char* p;
        strtod(s.c_str(), &p);
        return *p == 0;
    }
    

提交回复
热议问题