Facebook Page Twitter Page LinkedIn Page
× C Standard Library


The C <stdlib.h> atol() function is used to interpret an integer value in a byte string pointed to by str.

The function first discards any whitespace characters until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by numeric digits. The string may contain additional characters after those that form the integral number, which are ignored.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists (because either empty or contains only whitespaces), no conversion is performed and zero is returned.

Syntax

long int atol ( const char * str );

Parameters

str Specify pointer to the null-terminated byte string to be interpreted.

Return Value

On success, the function returns the converted integral number as a long int value. If no conversion can be performed, ​0​ is returned. If the converted value falls out of the range of long int type, the return value is undefined.

Example:

The below example shows the usage of <stdlib.h> atol() function.

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

int main (){
  char str1[] = "123";
  char str2[] = "10.55";
  char str3[] = "100 some words";
  char str4[] = "some words 555";

  long int num1 = atol(str1);
  long int num2 = atol(str2);
  long int num3 = atol(str3);
  long int num4 = atol(str4);

  //displaying the result
  printf("atol(\"%s\") = %ld\n", str1, num1);
  printf("atol(\"%s\") = %ld\n", str2, num2);
  printf("atol(\"%s\") = %ld\n", str3, num3);
  printf("atol(\"%s\") = %ld\n", str4, num4);

  return 0;
}

The output of the above code will be:

atol("123") = 123
atol("10.55") = 10
atol("100 some words") = 100
atol("some words 555") = 0

❮ C <stdlib.h> Library