strtol Function Introduction
The strtol function converts a string to a long integer in C. Its prototype is defined in the <stdlib.h> header file:
clong int strtol(const char *str, char **endptr, int base);
stris a pointer to the string to be converted.endptris a pointer to a pointer that stores the address of the first character remaining after conversion.baseis the radix for conversion, specified as a number between 2 and 36 or the special value 0.
Correct Usage of strtol
-
Specify the appropriate radix: The
baseparameter determines the radix of the string. For example, if the string begins with '0x' or '0X', setbaseto 16. Ifbaseis 0,strtolautomatically infers the radix based on the prefix: '0x' for hexadecimal, '0' for octal, or no prefix for decimal. -
Error Handling: Always check for and handle potential errors when using
strtol:- Invalid Input: If no conversion occurs,
strtolreturns 0, which can be confirmed by checking ifendptrequalsstr. - Overflow: If the converted value exceeds the range of
long int,strtolreturnsLONG_MAXorLONG_MINand setserrnotoERANGE.
- Invalid Input: If no conversion occurs,
-
Use
endptrto identify the conversion endpoint:endptrindicates the position after the numeric part, which is crucial for parsing complex strings. You can then process the remaining string based on this pointer.
Example
Consider a string containing mixed data where we want to extract and convert the integer value:
c#include <stdio.h> #include <stdlib.h> #include <errno.h> int main() { const char *data = "123ABC456"; char *endptr; long int value; errno = 0; // Reset errno to detect overflow value = strtol(data, &endptr, 10); if (endptr == data) { printf("No digits were found\n"); } else { printf("The number (long int) is %ld\n", value); } if (errno == ERANGE) { if (value == LONG_MAX) { printf("Overflow occurred: value is equal to LONG_MAX\n"); } else if (value == LONG_MIN) { printf("Underflow occurred: value is equal to LONG_MIN\n"); } } printf("Remaining text is: %s\n", endptr); return 0; }
In this example, the program correctly converts the string "123ABC456" to the long integer 123 and identifies "ABC456" as the remaining text.
Summary
As demonstrated, strtol is not limited to simple numeric conversions; it can handle complex string parsing and effectively manage error detection and handling. Using strtol correctly enhances program robustness and flexibility when processing external input.