Strtoul c – strtoul C Library Function

Strtoul c: The function strtoul converts a string to a unsigned long integer number of given base. The strtoul function also sets the endptr to point to the first character in str after the unsigned long integer number.

The function skips all white-space characters at the beginning of the string until the first non-whitespace character is found. Then it converts the subsequent characters into an unsigned long integer number of given base.

Function prototype of strtoul

unsigned long int strtoul(const char *str, char **endptr, int base);
  • str : A pointer to a string beginning with the representation of an unsigned long integer number.
  • endptr : This is a pointer to a pointer of type char, whose value is set by the function to point to the first character after the unsigned long integer number.
  • base : This the base(radix) of number. It must be between 2 and 36 inclusive or special value 0.

Return value of strtoul

Strtoul in c: This function returns the converted unsigned long integer number otherwise it returns zero, If no valid conversion could be performed.

C program using strtoul function

C strtoul: The following program shows the use of strtoul function for string to unsigned long integer number conversion.

strtoul C Library Function

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    char string[100], *ptr;
    long value;
    int base = 10;
     
    printf("Enter a string\n");
    gets(string);
     
    /* String to Unsigned long integer conversion */
    value = strtoul(string, &ptr, base);
    printf("Unsigned long integer value : %lu\n", value);
    printf("String after unsigned long number : %s\n", ptr);
      
    return 0;
}

Output

Enter a string
1234techcrashcourse
Unsigned long integer value : 1234
String after unsigned long number : techcrashcourse