How do you get an unsigned long out of a string?

Daniel Bingham picture Daniel Bingham · Sep 27, 2009 · Viewed 20.5k times · Source

What's the safest and best way to retrieve an unsigned long from a string in C++?

I know of a number of possible methods.

First, converting a signed long taken from atol.

char *myStr; // Initalized to some value somehow.
unsigned long n = ((unsigned)atol(myStr));

The obvious problem with this is, what happens when the value stored in myStr is larger than a signed long can contain? What does atol retrieve?

The next possibility is to use strtoul.

char *myStr; // Initalized to some value somehow.
unsigned long n = strtoul(myStr, 0, 10);

However, this is a little over complicated for my needs. I'd like a simple function, string in, unsigned long base 10 out. Also, the error handling leaves much to be desired.

The final possibility I have found is to use sscanf.

char *myStr; // Initalized to some value somehow.
unsigned long n = 0;
if(sscanf(myStr, "%lu", n) != 1) {
    //do some error handling
}

Again, error handling leaves much to be desired, and a little more complicated than I'd like.

The remaining obvious option is to write my own either a wrapper around one of the previous possibilities or some thing which cycles through the string and manually converts each digit until it reaches ULONG_MAX.

My question is, what are the other options that my google-fu has failed to find? Any thing in the C++ std library that will cleanly convert a string to an unsigned long and throw exceptions on failure?

My apologies if this is a dupe, but I couldn't find any questions that exactly matched mine.

Answer

Patrice Bernassola picture Patrice Bernassola · Sep 27, 2009

You can use strtoul with no problem. The function returns an unsigned long. If convertion can not be performed the function return 0. If the correct long value is out of range the function return ULONG_MAX and the errno global variable is set to ERANGE.