Unleashing the Power of strtol() in C++

How strtol() Works

The strtol() function takes three parameters: a string, a pointer to a character, and an integer value representing the base. It interprets the string as an integral number of the given base and returns a long integer value. If no valid conversion can be performed, it returns 0.

long int strtol(const char *str, char **endptr, int base);

The Anatomy of a Valid Integer Value

A valid integer value for strtol() consists of:

  • An optional + or – sign
  • A prefix 0 for octal base (when base = 8 or 0)
  • A prefix 0x or 0X for hexadecimal base (when base = 16 or 0)
  • A sequence of digits and/or alphabets (when base is greater than 10)

Bases and Valid Digits

The valid values for the base parameter range from 0 to 36. For bases 2 to 10, valid digits include only numbers. However, for bases 11 to 36, valid digits include alphabets. For example, the set of valid digits for base 11 is {0, 1, …, 9, A, a}.

// Example: base 11
char str[] = "12A";
char* endptr;
long int num = strtol(str, &endptr, 11);
// num = 172 (12*A + 10)

Handling Leading Whitespace and Invalid Conversions

The strtol() function ignores all leading whitespace characters until it finds the primary non-whitespace character. It then takes as many characters as possible that form a valid integer representation and converts them to a long integer value. Whatever is left of the string after the last valid character is ignored.

char str[] = "   123abc";
char* endptr;
long int num = strtol(str, &endptr, 10);
// num = 123
// *endptr points to "abc"

Automatic Base Detection

When the base is 0, the numeric base is determined automatically by looking at the format of the string. If the prefix is 0, the base is octal (8). If the prefix is 0x or 0X, the base is hexadecimal (16), otherwise the base is decimal (10).

char str[] = "012";
char* endptr;
long int num = strtol(str, &endptr, 0);
// num = 10 (octal base)

char str[] = "0xA";
char* endptr;
long int num = strtol(str, &endptr, 0);
// num = 10 (hexadecimal base)

Examples and Applications

With its versatility and power, the strtol() function has numerous applications in C++ programming. From parsing configuration files to processing user input, this function is an essential tool in any programmer’s toolkit.

// Example: parsing configuration file
char line[] = "port=8080";
char* endptr;
long int port = strtol(line + 5, &endptr, 10);
// port = 8080
// Example: processing user input
char input[] = "12abc";
char* endptr;
long int num = strtol(input, &endptr, 10);
// num = 12
// *endptr points to "abc"

Leave a Reply