C programming stdlib.h function - long int strtol(const char *str, char **endptr, int base)

The strtol function in the stdlib.h library of the C programming language is used to convert a string that represents a long integer into a long int value. The syntax of the strtol function is as follows:

long int strtol(const char *str, char **endptr, int base);
Sou‮ecr‬:www.theitroad.com

Here, the argument str is a pointer to the null-terminated string to be converted, endptr is a pointer to a char * variable, and base is an integer that specifies the base of the number to be converted.

The strtol function scans the input string pointed to by str, and converts it to a long int value using the specified base. The function stops scanning the input string when it encounters the first character that cannot be part of a long integer in the specified base. The function returns the converted value as a long int value.

If endptr is not NULL, the strtol function sets *endptr to the first character in str that is not part of the number being converted.

For example, the following code uses the strtol function to convert a string representing a long integer in base 16 into a long int value:

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

int main() {
   char str[] = "1A5";
   char *endptr;
   long int value;
   value = strtol(str, &endptr, 16);
   printf("The converted value is: %ld\n", value);
   return 0;
}

In this example, the input string is the null-terminated string "1A5". The strtol function converts this string to the long integer value 421, which is stored in the value variable. The program then uses the printf function to print the converted value. The output of the program is:

The converted value is: 421

Note that the strtol function returns 0 if the input string is not a valid long integer in the specified base. If endptr is not NULL, the strtol function sets *endptr to the first character in str that is not part of the number being converted. If the entire input string is part of the number being converted, *endptr is set to the null character ('\0'). It is the responsibility of the caller to check the value of *endptr to determine if the conversion was successful.