C Data Type Functions - C atol






Converts a string to a long integer.

long int atol(const char *str );

The string str is converted to a long integer (type long int).

Any initial whitespace characters are skipped.

The number may consist of an optional sign and a string of digits.

Conversion stops when the first unrecognized character is reached.

Prototype

long int atol ( const char * str );

Parameter

This function has the following parameter.

str
C-string containing the representation of an integral number.

Return

The function returns the converted integral number as a long int value.

If no valid conversion could be performed, a zero value is returned.

If the converted value would be out of the range of representable values by a long int, it causes undefined behavior.





Example


#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atol */
// w w  w  .  ja  v a 2  s  . co m
int main (){
  long int li;
  char buffer[256];
  printf ("Enter a long number: ");
  fgets (buffer, 256, stdin);
  li = atol(buffer);
  printf ("The value entered is %ld. Its double is %ld.\n",li,li*2);
  return 0;
} 

       

The code above generates the following result.