atol() in C – Syntax, Use and Example

Write a C program to input string representation of integer and convert string to long using atol() function. How to convert string to long using atol() function.

atol() library function

atol() function converts string representation of integer to long type. It is defined in stdlib.h header file.

Syntax of atol() function

long int atol (const char * str);
  • It accepts pointer to constant character str i.e. the sting representation of integer.
  • It returns long int. If str is a valid integer string then it returns str as long int type otherwise return 0L.

Important note:

Example program to use atol() function

/**
 * C program to convert string to long using atol() library function.
 */

#include <stdio.h>
#include <stdlib.h>     // Used for atol()


int main()
{
    char number[30];
    long bigNum;


    /* Input string representation of integer from user. */
    printf("Enter any integer: ");
    fgets(number, 30, stdin);


    /* Convert string representation of number to integer */
    bigNum = atol(number);


    /* Use %d, %i, %l, %ld, %li to print long type */
    printf("Converted long int = %ld\n", bigNum);


    return 0;
}

Output

Enter any integer: 12
Converted long int = 12

Enter any integer: 999999999
Converted long int = 999999999

Enter any integer: -999999999
Converted long int = -999999999

Enter any integer: a
Converted long int = 0

Enter any integer: 1 2 3
Converted long int = 1

Enter any integer: aaaaaaaaaaaaaasdddddddddd
Converted long int = 0

Enter any integer: 1.533
Converted long int = 1

Enter any integer: -99999999999999999999999999999
Converted long int = 1610612737

Enter any integer: 99999999999999999999999999999999999
Converted long int = -1

Enter any integer: 11111111a
Converted long int = 11111111

Enter any integer: aaaaa111111111
Converted long int = 0

Happy coding 😉