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

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

    I just wanted to throw in this idea that uses iteration but some other code does that iteration:

    #include 
    
    bool is_number(const std::string& s)
    {
        return( strspn( s.c_str(), "-.0123456789" ) == s.size() );
    }
    

    It's not robust like it should be when checking for a decimal point or minus sign since it allows there to be more than one of each and in any location. The good thing is that it's a single line of code and doesn't require a third-party library.

    Take out the '.' and '-' if positive integers are all that are allowed.

提交回复
热议问题