How to Convert Char Array to Int in C++

In C++, a character array is treated as a sequence of characters also known as a string. Converting a character array into an integer is a common task that can be performed using various methods and in this article, we will learn how to convert char array to int in C++.

Example

Input:
char arr1[] ="123456"

Output:
123456

Convert Char Array to Int in C++

To convert a char array to int in C++, we can use the atoi() function provided by the <cstdlib> header. Following is the syntax to use atoi function:

Syntax of atoi()

int atoi(const char arr)

where:

  • arr: is the name of the character array.
  • return type: Integer equivalent to the character array or 0 if the input was not valid.

C++ Program to Convert Char Array to Int

The following program illustrates how we can convert a char array to int in C++ using the atoi function:

C++
// C++ Program to Convert Char Array to Int
#include <iostream>
#include <cstdlib>  
using namespace std;

int main() {
    char str[] = "12345";
    int num = atoi(str);
    cout << "The integer value is: " << num << endl;
    return 0;
}

Output
The integer value is: 12345

Time Complexity: O(N), where N is the length of the character array.
Auxiliary Space: O(1)


Contact Us