Search code examples
c++stringstrtoull

How to parse a string containing an integer and check if greater than a maximum in c++


I want to determine (in c++) if a string contains a number that is in the range 0 - UINT_MAX I have tried atoi etc but that don't handle this case. For example the string 42949672963 would fail the test Has anyone got any suggestions?


Solution

  • You can use the standard C++ function std::strtoul and then check whether the converted number is not greater than std::numeric_limits<unsigned int>::max().

    For example

    #include <iostream>
    #include <string>
    #include <stdexcept>
    #include <limits>
    
    int main() 
    {
        std::string s( "42949672963" );
        unsigned int n = 0;
    
        try
        {
            unsigned long tmp = std::stoul( s );
    
            if ( std::numeric_limits<unsigned int>::max() < tmp )
            {
                throw std::out_of_range( "Too big number!" );
            }
    
            n = tmp;
        }
        catch ( const std::out_of_range &e )
        {
            std::cout << e.what() << '\n';
        }
    
        std::cout << "n = " << n << '\n';
    
        return 0;
    }
    

    The program output is

    Too big number!
    n = 0
    

    You can also add one more catch for invalid number representations.

    Another way is to use the standard C function strtoul if you do not want to deal with exceptions.