atoi(3)
C library function
Converts the start of a string to an int. atoi reports no errors: “abc” and “0” both give 0, and an overflow is undefined behavior.
#include <stdlib.h>
int atoi(const char *nptr);Description
atoi reads the start of the string nptr as a base 10 integer. It skips leading whitespace (space, tab, newline and the other isspace characters), accepts one + or - sign, then reads digits and stops at the first character that is not one. The rest of the string is ignored without a warning.
The standard defines it as equivalent to (int)strtol(nptr, NULL, 10), except on error, where it promises nothing.
Return value
The integer read. When the string does not start with a digit, glibc and musl return 0; POSIX leaves that value unspecified. If the number does not fit in an int, the C standard says the behavior is undefined. atoi is not required to set errno, and the Linux man page warns that you cannot rely on it to tell a 0 from an error.
Pitfalls
You cannot tell an error from a real zero: atoi("abc") and atoi("0") return the same thing. For user input, that rules it out.
Trailing characters go unnoticed: " -17abc" gives -17 as if the input were clean.
A number that is too large is not reported. In the example, "3000000000" exceeds INT_MAX (2,147,483,647) and glibc returns -1294967296, a negative number out of nowhere. That is what it does on this machine, not a guarantee: the standard gives none.
Only base 10 is read: atoi("0x1A") stops at the x and returns 0.
The Linux man page recommends strtol(3) for any new program. It tells you where parsing stopped, reports overflow through errno and accepts other bases. Keep atoi for data you control, such as a constant in a file you wrote yourself.
Example
#include <stdio.h>#include <stdlib.h>
int main(void){ const char *inputs[] = {"42", " -17abc", "abc", "0", "3000000000"};
for (int i = 0; i < 5; i++) printf("atoi(\"%s\") = %d\n", inputs[i], atoi(inputs[i])); return 0;}$ gcc -Wall -Wextra conversion.c -o conversion$ ./conversionatoi("42") = 42atoi(" -17abc") = -17atoi("abc") = 0atoi("0") = 0atoi("3000000000") = -1294967296Lines 3 and 4 of the output are identical, yet one is an error and the other a real zero. The last line is an overflow that nothing reports.
atoi
Write gm_atoi, your own atoi, which skips leading whitespace, takes one optional sign and stops at the first character that is not a digit.