How to check std::string if its indeed an integer?

前端 未结 3 1642
夕颜
夕颜 2020-12-07 02:41

The following code converts an std::string to int and the problem lies with the fact that it cannot discern from a true integer or just a random st

3条回答
  •  青春惊慌失措
    2020-12-07 03:24

    WhozCraig's approach is much nicer and I wanted to expand on it using the approach that the C++ FAQ uses which is as follows:

    #include 
    #include 
    #include 
    #include 
    
    class BadConversion : public std::runtime_error {
    public:
      BadConversion(std::string const& s)
        : std::runtime_error(s)
        { }
    };
    
    
    
    inline int convertToInt(std::string const& s,
                                  bool failIfLeftoverChars = true)
    {
      std::istringstream i(s);
      int x;
      char c;
      if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
        throw BadConversion("convertToInt(\"" + s + "\")");
      return x;
    }
    
    
    int main()
    {
        std::cout << convertToInt( "100" ) << std::endl ;
        std::cout << convertToInt( "-100" ) << std::endl ;
        std::cout << convertToInt( "  -100" ) << std::endl ;
        std::cout << convertToInt( "  -100  ", false ) << std::endl ;
    
        // The next two will fail
        std::cout << convertToInt( "  -100  ", true ) << std::endl ;
        std::cout << convertToInt( "H" ) << std::endl ;
    }
    

    This is robust and will know if the conversion fails, you also can optionally choose to fail on left over characters.

提交回复
热议问题