Gunner
Gunner

Reputation: 135

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?

Upvotes: 1

Views: 1843

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

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.

Upvotes: 2

SteveTheGrk
SteveTheGrk

Reputation: 352

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 .

Upvotes: 1

Serve Laurijssen
Serve Laurijssen

Reputation: 9753

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

Upvotes: 1

Related Questions