1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Gunner
  • 125
  • 10

3 Answers3

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

The modern way is to use std::stoi, std::stoll etc

There are overloads for string and wstring and the can handle the larger sizes.

https://en.cppreference.com/w/cpp/string/basic_string/stol

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
1

You may search the string character by character in a loop and every time you have continously digits appeared you can be building up an integer and at the same time be checking with the Max UINT .

SteveTheGrk
  • 352
  • 1
  • 7