HOWTO · C++

How to Convert Char Array to Int in C++

This article demonstrates ways to convert a char array to int type in C++.

On this page

A null-terminated char array can hold text that represents an integer. C++ provides several ways to parse that text, but the functions differ in how they report errors and whether they accept a numeric prefix followed by other characters. Choose based on whether the input is trusted and whether the whole array must contain a valid number.

The examples use decimal input. A successful prefix conversion does not necessarily mean that every character was consumed: for example, parsing "23323tail" can produce 23323 and leave tail unparsed. If the complete input must be numeric, check the parser’s end position as well as its conversion result.

Use the std::strtol Function to Convert a char Array to an int

std::strtol parses a null-terminated character sequence and returns a long. Its third argument selects the base: use 10 for decimal, 16 for hexadecimal, or 0 to infer a base from a prefix. For bases other than zero, the valid range is 2 through 36.

The second argument receives a pointer to the first character that was not consumed. If it still points to the start of the input, no digits were parsed. If it points to the terminating null character, the entire string was consumed. Set errno to zero before calling the function and check for ERANGE afterward to detect a result outside the range of long. Since the result is a long, also compare it with std::numeric_limits<int>::min() and max() before storing it in an int.

Run this example. It uses decimal text stored in a null-terminated character array and prints the parsed integer.

#include <cerrno>
#include <cstdlib>
#include <iostream>
#include <limits>

int main() {
  const char input[] = "23323";
  char* end = nullptr;
  errno = 0;
  const long parsed = std::strtol(input, &end, 10);

  if (end == input || *end != '\0' || errno == ERANGE ||
      parsed < std::numeric_limits<int>::min() ||
      parsed > std::numeric_limits<int>::max()) {
    std::cout << "Could not convert the complete input.\n";
    return 0;
  }

  const int value = static_cast<int>(parsed);
  std::cout << value << '\n';
}

The supplied runtime run for this success case exited with code 0 and produced:

23323

The run covers this valid input only; it does not establish behavior for failed conversions or out-of-range values. Keep the checks for production input: they distinguish no conversion, leftover characters, a long range error, and a value that cannot fit in int.

Use the std::atoi Function to Convert a char Array to an int

std::atoi is a short option when the input is already trusted and well formed:

int value = std::atoi(input);

It accepts leading whitespace and an optional sign, then parses decimal digits. Like other prefix parsers, it can stop at a non-digit and ignore the remaining characters. It does not provide a dependable way to distinguish a valid zero from a failed conversion or a useful error channel for range failures. If the parsed value is not representable as an int, the behavior is undefined; do not use std::atoi on unchecked or untrusted numeric input. Use std::strtol when input may be malformed or out of range, or when the caller needs conversion diagnostics and an explicit int range check.

Use the std::sscanf Function to Convert a char Array to an int

std::sscanf applies a format to text and reports how many conversions succeeded. For one integer, check that the return value is 1 before using the destination:

int value = 0; int converted = std::sscanf(input, "%d", &value);

%d accepts leading whitespace and an optional sign, then reads decimal digits. It may successfully parse a prefix while leaving trailing text unread; use an additional format check or another parsing method when full consumption matters. The destination must be a real, writable int object, and it must not be read unless the conversion count confirms that a conversion occurred. That count does not make an unrepresentable result safe: if the matched value cannot be represented by int, the behavior is undefined. Do not use %d for unchecked or untrusted numeric input that may be out of range. For this simple task, std::strtol makes end-position and range checks more explicit.

Use a Loop to Convert a char Array to an int

A loop is appropriate when the accepted syntax is intentionally custom. Define that syntax first. For example, a decimal parser might accept an optional leading + or -, require at least one digit, and reject every other character. It must also check before each multiply-and-add that the next digit will remain within the chosen integer range. Otherwise, signed overflow can make the result incorrect or invoke undefined behavior.

Do not skip arbitrary non-digits and append later digits: turning "23tail4" into 234 is filtering characters, not parsing an integer. A complete custom parser must handle sign placement, digit validation, full input consumption, and overflow. Unless those custom rules are necessary, use std::strtol and its end pointer instead.

Conclusion

For general conversion, prefer std::strtol: it provides the stopping position and a way to detect long range errors, and its result can be checked against the int limits before conversion. Use std::atoi only for trusted, well-formed input where detailed diagnostics are unnecessary. Choose std::sscanf when formatted parsing is useful and check its conversion count. Write a loop when the program needs a deliberately different input grammar, and implement sign, digit, full-consumption, and overflow checks explicitly.