strtol : <stdlib.h> library function

The function long int strtol(const char *str, char **endptr, int base); converts a string to a long integer number of given base. The strtol function also sets the endptr to point to the first character in str after the 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 a long integer number of given base.

Function prototype of strtol

long int strtol(const char *str, char **endptr, int base);
  • str : A pointer to a string beginning with the representation of a 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 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 strtol

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

C program to show the use of strtol function

The following program shows the use of strtol function for string to long integer number conversion.

#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 Long integer conversion */
    value = strtol(string, &ptr, base);
    printf("Long integer value : %ld\n", value);
    printf("String after a number(Long) : %s\n", ptr);
     
    return 0;
}

Program Output
Enter a string
1234techcrashcourse
Long integer value : 1234
String after a number(Long) : techcrashcourse
Enter a string
1234.55techcrashcourse
Long integer value : 1234
String after a number(Long) : .55techcrashcourse