What is atol() in C++?

The atol() function in C++ is used to convert a string to an integer data-type long int. atol() interprets the contents of the string as an integer.

Library

To use the atol() function, include the following library:

#include <cstdlib>

Declaration

The atol() function can be declared as:

long int atol(const char* str);
  • str: The string to be converted to an integer.

Return value

The atol() function returns a long int type variable that is the integer interpretation of the string str.

Note: The atol() function returns 0 if:

  • str is empty.
  • str contains only whitespace characters.
  • The sequence of non-whitespace characters in str is not a valid integer.
  • Non-numeric characters are placed before numeric characters.

Examples

Example 1

Consider the code snippet below, which demonstrates the use of the atol() function:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
char str1[] = "123";
char str2[] = "-123";
char str3[] = "12end with words";
long int asint1 = atol(str1);
cout<<"atol( "<<str1<<" ) = "<<asint1<<endl;
long int asint2 = atol(str2);
cout<<"atol( "<<str2<<" ) = "<<asint2<<endl;
long int asint3 = atol(str3);
cout<<"atol( "<<str3<<" ) = "<<asint3<<endl;
return 0;
}

Explanation

Three strings, str1, str2, and str3, are declared in lines 8-10. The atol() function is used in line 12, line 15, and line 18 to convert str1, str2, and str3 to integers, respectively.

Example 2

Consider the code snippet below, which demonstrates when the atol() function returns 0:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
char str1[] = "";
char str2[] = " \t ";
char str3[] = "abc";
char str4[] = "start with words12";
long int asint1 = atol(str1);
cout<<"atol( "<<str1<<" ) = "<<asint1<<endl;
long int asint2 = atol(str2);
cout<<"atol( "<<str2<<" ) = "<<asint2<<endl;
long int asint3 = atol(str3);
cout<<"atol( "<<str3<<" ) = "<<asint3<<endl;
long int asint4 = atol(str4);
cout<<"atol( "<<str4<<" ) = "<<asint4<<endl;
return 0;
}

Explanation

Four strings, str1, str2, str3, and str4, are declared in lines 8-11.

  • line 13: The atol() function is used to convert str1 to an integer. The atol() function returns 0, as str1 is empty.
  • line 16: The atol() function is used to convert str2 to an integer. The atol() function returns 0, as str2 only contains whitespace characters.
  • line 19: The atol() function is used to convert str3 to an integer. The atol() function returns 0, as non-whitespace characters of str3 do not represent a valid integer.
  • line 22: The atol() function is used to convert str4 to an integer. The atol() function returns 0, as non-numeric characters are placed before numeric characters of str4.
Copyright ©2024 Educative, Inc. All rights reserved