atoi() function in C++

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

1. atoi() Function Overview

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

Signature:

int atoi(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 = "1234";
    const char* number_str2 = "-987";
    const char* invalid_str = "123abc";

    int num1 = atoi(number_str1);
    int num2 = atoi(number_str2);
    int invalid_num = atoi(invalid_str);

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

    return 0;
}

Output:

String: 1234 as Integer: 1234
String: -987 as Integer: -987
String: 123abc as Integer: 123

3. Explanation

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

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

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

4. The output displays the converted integers.

Note: It's essential to be cautious when using atoi() since it doesn't report errors and might produce undefined behavior for some inputs. Consider using alternatives such as std::stoi which throws exceptions on invalid input.


Comments