atol() function in C++

In this guide, you will learn what is atol() function is in C++ programming and how to use it with an example.

1. atol() Function Overview

The atol() function, part of the C++ standard library <cstdlib>, converts a string to a long integer (long). If the given string has no valid conversion, the behavior is undefined.

Signature:

long int atol(const char *str);

Parameters:

- str: A pointer to the null-terminated string that represents a valid integer number.

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    const char* number_str1 = "1234567890";
    const char* number_str2 = "-9876543210";
    const char* invalid_str = "123456abc";

    long int num1 = atol(number_str1);
    long int num2 = atol(number_str2);
    long int invalid_num = atol(invalid_str);

    std::cout << "String: " << number_str1 << " as Long Integer: " << num1 << std::endl;
    std::cout << "String: " << number_str2 << " as Long Integer: " << num2 << std::endl;
    std::cout << "String: " << invalid_str << " as Long Integer: " << invalid_num << std::endl;

    return 0;
}

Output:

String: 1234567890 as Long Integer: 1234567890
String: -9876543210 as Long Integer: -9876543210
String: 123456abc as Long Integer: 123456

3. Explanation

1. We have three strings: number_str1, number_str2, and invalid_str. The first two represent valid long integer numbers, while the third one is a mix of characters and numbers.

2. The atol() function converts each string to its long integer representation.

3. In the case of invalid_str, atol() stops reading the string as soon as it encounters the first character that isn't a valid part of a long integer.

4. The output displays the converted long integers.

Note: It's crucial to be cautious when using atol() since it doesn't report errors and might produce undefined behavior for some inputs. For more robust error handling, consider using alternatives such as std::stol which throws exceptions on invalid input.


Comments