What atoi() does
atoi is a function from the C standard library. It’s declared in <stdlib.h>, and C++ code can get it from <cstdlib>. It takes a string and returns an int:
int atoi(const char *str);
It reads from the start of the string. It skips leading whitespace, accepts an optional + or - sign, and then reads decimal digits. It stops at the first character that isn’t a digit and ignores anything after that.
Readers coming from Python often ask Can you use int() on a string? C doesn’t have a conversion like that built into the language, so atoi fills a similar role.
Here’s a short example:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%d\n", atoi(" 42 apples")); /* prints 42 */
printf("%d\n", atoi("-7")); /* prints -7 */
printf("%d\n", atoi("apples")); /* prints 0 */
return 0;
}
The first call skips the spaces, reads 42, and ignores the rest of the string.
What it returns for bad input
If the string doesn’t start with a number, after any whitespace and an optional sign, atoi returns 0. That creates a problem. atoi("0") also returns 0, so the return value alone doesn’t tell you whether the conversion failed.
What happens with huge values
The C standard says that if the value can’t be represented as an int, the behavior is undefined. That means the result can’t be relied on, and a program that depends on it may behave in unexpected ways. The usual example is a number larger than the biggest int on your system. Don’t use atoi for text you don’t control, such as input typed by a user.
How atoi relates to strtol
Apart from how errors are handled, atoi is equivalent to (int)strtol(str, NULL, 10). The function strtol gives you more control. It can report where parsing stopped through its end pointer, and it sets errno to ERANGE when the value is out of range. atoi gives you neither.
Which function to use in C++
If you’re writing C++, prefer the functions covered in c convert string to int. They report errors with exceptions or error codes, instead of returning 0 for bad input.
Summary
atoi is short and simple, and you’ll see it in older code. Its main weakness is that it hides errors. Know that bad input returns 0 and that out-of-range values are undefined. When the input isn’t trusted, use strtol in C or the C++ functions instead.