C++ atol()

The atol() function in C++ interprets the contents of a string and returns its corresponding integer value.

atol() Prototype

long int atol(const char* str);

It is defined in <cstdlib> header file.


The atol() function takes string as parameter, interprets its content as an integral number and returns corresponding value in long int.

atol() Parameters

  • str - A string having the representation of an integral number.

atol() Return value

The atol() function returns:

  • a long int value (which is converted from the string).
  • 0 if no valid conversion could be performed.

If the converted value is out of the range, it causes undefined behavior.


Example 1: How atol() function works?

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	char s[] = "-114"; 
	double number;
	cout << "Number in String = " << s << endl;

	number = atol(s);
	cout << "Number in Long Int = " << number;
	
	return 0;
}

When you run the program, the output will be:

Number in String = -114
Number in Long Int = -114

A valid integer value for atol() function consists of an optional + or - sign followed by numeric digits (0-9). The atol() function doesn't support hexadecimal, infinity and NaN expression like atof() function.

In general, a valid integer argument for atol() function has the following form:

[whitespace] [- | +] [digits]

The atol() function ignores all the leading whitespace characters until the primary non-whitespace character is found.

Then, beginning from this character, it takes as many characters as possible that forms a valid integer representation and converts them to a long int value. Whatever is left of the string after the last valid character is ignored and has no effect on the result.


Example 2: atol() function with Whitespace and trailing characters

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	cout << "Number in String = " << "    13" << endl;
	cout << "Number in Long Int = " << atol("    13") << endl << endl;
	
	cout << "Number in String = " << "  25    " << endl;
	cout << "Number in Long Int = " << atol("  25    ") << endl << endl;
	
	cout << "Number in String = " << "41.90abcd" << endl;
	cout << "Number in Long Int = " << atol("41.90abcd") << endl << endl;
	
	// Returns 0 because of invalid conversion
	cout << "abcd14" << " to Long Int = " << atol("abcd14") << endl;

	return 0;
}

When you run the program, the output will be:

Number in String =     13
Number in Long Int = 13

Number in String =   25    
Number in Long Int = 25

Number in String = 41.90abcd
Number in Long Int = 41

abcd14 to Long Int = 0