strtol() Function

The strtol() function is declared in the header file <stdlib.h>.

The strtol() function converts a string into a long integer by parsing its content based on a specified numerical base. It handles optional leading whitespace, an optional sign, and an optional base prefix when the base is zero or 16. This function is useful for extracting numerical values from strings while also providing a pointer to the remainder of the string.


Syntax of strtol()

</>
Copy
long int strtol(const char *str, char **endptr, int base);

Parameters

ParameterDescription
strC-string that begins with the representation of an integral number.
endptrPointer to a pointer to character. On return, it points to the first character after the numerical value in str. Can be NULL if not used.
baseNumerical base (radix) used for conversion. If 0, the base is determined by the format of str (e.g., “0” for octal, “0x” for hexadecimal).

It is worth noting that the function discards leading whitespace and interprets an optional sign before converting the number. Additionally, if the converted value is outside the range of representable values for a long int, strtol() returns LONG_MAX or LONG_MIN and sets errno to ERANGE.


Return Value

On success, strtol() returns the converted integral number as a long int. If no valid conversion is performed, it returns 0L. In case of overflow or underflow, it returns LONG_MAX or LONG_MIN respectively, and sets errno to ERANGE.


Examples for strtol()

Example 1: Basic Conversion from String to Long Integer (Base 10)

This example demonstrates a simple conversion of a string containing a decimal number into a long integer using base 10.

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *numStr = "  12345";
    char *end;
    long int num = strtol(numStr, &end, 10);

    printf("Converted number: %ld\n", num);
    printf("Remaining string: \"%s\"\n", end);

    return 0;
}

Explanation:

  1. Leading whitespace is skipped.
  2. The string “12345” is converted to the long integer 12345 using base 10.
  3. The pointer end points to the end of the numeric portion.

Program Output:

Converted number: 12345
Remaining string: ""

Example 2: Conversion with Base Detection and Extra Characters

This example shows how strtol() converts a string to a long integer while also setting the end pointer to the first character that is not part of the number.

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *numStr = "  -789xyz";
    char *end;
    long int num = strtol(numStr, &end, 0);  // Base 0 for automatic detection

    printf("Converted number: %ld\n", num);
    printf("Remaining string: \"%s\"\n", end);

    return 0;
}

Explanation:

  1. Whitespace is skipped and the sign is detected, converting “-789” to -789.
  2. Base 0 enables automatic base detection.
  3. The pointer end points to “xyz”, the part of the string following the numeric portion.

Program Output:

Converted number: -789
Remaining string: "xyz"

Example 3: Conversion from a Hexadecimal String

This example demonstrates how to convert a hexadecimal string to a long integer. An optional “0x” prefix is used to denote hexadecimal values.

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *hexStr = "  0x1A3F";
    char *end;
    long int num = strtol(hexStr, &end, 16);

    printf("Converted hexadecimal: %ld\n", num);
    printf("Remaining string: \"%s\"\n", end);

    return 0;
}

Explanation:

  1. Leading whitespace and the “0x” prefix are handled.
  2. The hexadecimal digits “1A3F” are converted to their decimal equivalent.
  3. The pointer end points to the end of the numeric portion.

Program Output:

Converted hexadecimal: 6719
Remaining string: ""

Example 4: Handling Invalid Input and Overflow

This example illustrates how strtol() behaves when given an invalid input and demonstrates error handling for overflow conditions.

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

int main() {
    const char *invalidStr = "notanumber";
    char *end;
    errno = 0; // Clear errno before conversion
    long int num = strtol(invalidStr, &end, 10);

    if (end == invalidStr) {
        printf("No valid conversion could be performed.\n");
    } else {
        printf("Converted number: %ld\n", num);
    }
    
    // Example of overflow: a very large number
    const char *overflowStr = "9999999999999999999999";
    errno = 0; // Reset errno
    num = strtol(overflowStr, &end, 10);
    if (errno == ERANGE) {
        printf("Overflow occurred. num = %ld\n", num);
    } else {
        printf("Converted number: %ld\n", num);
    }

    return 0;
}

Explanation:

  1. The first conversion attempts to convert “notanumber”. Since there is no valid numeric representation, end remains unchanged and a message is printed indicating failure.
  2. The second conversion demonstrates handling overflow by attempting to convert a very large number. When overflow occurs, errno is set to ERANGE and the function returns LONG_MAX or LONG_MIN.

Program Output:

No valid conversion could be performed.
Overflow occurred. num = 9223372036854775807