atol() in C

The atol() function converts a C-style string (array of characters), passed as an argument to atol() function, to a long integer. It converts the C-string str to a value of type long int by interpreting the characters of the string as numerical values. It discards the leading whitespace characters until a non-whitespace character is found.

Syntax

long int atol ( const char * str );

Parameters

  • The function accepts one mandatory parameter str which represents an integral number.

Return Value

  • The function returns the long int representation of the string.
  • It returns ‘0’ if no valid conversion can be performed.

Note: If the C-string str passed to atol() function is either empty or contains only whitespace characters, it is not a valid integral number, no conversion will be performed and it will return zero.

Example: Program to Illustrate the Working of atol() Function.

C




// C program to illustrate
// working of atol() function.
#include <stdio.h>
// Include this header for atol function
#include <stdlib.h>
 
int main()
{
    // char array of numbers
    char str1[] = "5672345";
 
    // Function calling to convert to a long int
    long int num1 = atol(str1);
 
    printf("Number is %ld\n", num1);
 
    // char array of numbers without spaces
    char str2[] = "10000002 0";
 
    // Function calling to convert to a long int
    long int num2 = atol(str2);
 
    printf("Number is %ld\n", num2);
 
    return 0;
}


C++




// CPP program to illustrate
// working of atol() function.
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // char array of numbers
    char str1[] = "5672345";
 
    // Function calling to convert to a long int
    long int num1 = atol(str1);
 
    cout << "Number is " << num1 << "\n";
 
    // char array of numbers of spaces
    char str2[] = "10000002 0";
 
    // Function calling to convert to a long int
    long int num2 = atol(str2);
 
    cout << "Number is " << num2 << "\n";
    return 0;
}


Output

Number is 5672345
Number is 10000002

atol(), atoll() and atof() functions in C/C++

In C/C++, atol(), atoll(), and atof() are functions used to convert strings to numbers of different types. These functions are Standard Library functions. In this article, we will learn these String-to-number conversion functions in C/C++.

Similar Reads

1. atol() in C

The atol() function converts a C-style string (array of characters), passed as an argument to atol() function, to a long integer. It converts the C-string str to a value of type long int by interpreting the characters of the string as numerical values. It discards the leading whitespace characters until a non-whitespace character is found....

2. atoll() in C

...

3. atof() in C

...