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

h‮tt‬ps://www.theitroad.com

The strtoul function is a function in the C standard library that is used to convert a string representing an unsigned long integer to an actual unsigned long int value. The syntax of the strtoul function is as follows:

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

The str argument 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 strtoul function scans the input string pointed to by str, and converts it to an unsigned 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 an unsigned long integer in the specified base. The function returns the converted value as an unsigned long int value.

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

Here is an example that demonstrates how to use the strtoul function to convert a string to an unsigned long int:

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

int main(void) {
    char str[] = "1234567890";
    char *endptr;
    unsigned long int value = strtoul(str, &endptr, 10);

    printf("The converted value is: %lu\n", value);
    return 0;
}

In this example, the input string is the null-terminated string "1234567890", which is converted to an unsigned long int value of 1234567890 using the strtoul function. The program then uses the printf function to print the converted value. The output of the program is:

The converted value is: 1234567890

Note that the strtoul function returns 0 if the input string is not a valid unsigned long integer in the specified base. If endptr is not NULL, the strtoul 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.