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

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

    My solution using C++11 regex (#include ), it can be used for more precise check, like unsigned int, double etc:

    static const std::regex INT_TYPE("[+-]?[0-9]+");
    static const std::regex UNSIGNED_INT_TYPE("[+]?[0-9]+");
    static const std::regex DOUBLE_TYPE("[+-]?[0-9]+[.]?[0-9]+");
    static const std::regex UNSIGNED_DOUBLE_TYPE("[+]?[0-9]+[.]?[0-9]+");
    
    bool isIntegerType(const std::string& str_)
    {
      return std::regex_match(str_, INT_TYPE);
    }
    
    bool isUnsignedIntegerType(const std::string& str_)
    {
      return std::regex_match(str_, UNSIGNED_INT_TYPE);
    }
    
    bool isDoubleType(const std::string& str_)
    {
      return std::regex_match(str_, DOUBLE_TYPE);
    }
    
    bool isUnsignedDoubleType(const std::string& str_)
    {
      return std::regex_match(str_, UNSIGNED_DOUBLE_TYPE);
    }
    

    You can find this code at http://ideone.com/lyDtfi, this can be easily modified to meet the requirements.

提交回复
热议问题