atoi() Convert a string to int
atoi() Convert a string to int
atoi() converts a decimal prefix to int and returns 0 if no conversion can be performed. Invalid input looks like zero; out-of-range behavior is undefined.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
int atoi(const char *nptr);
⚙️ Parameters
| nptr Required | A null-terminated string optionally containing leading whitespace and a plus or minus sign. |
|---|
Returns: Returns the converted int value, or 0 if no valid initial conversion can be performed. Behavior is undefined if the result is outside the representable int range.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
42
-17
⚠️ Warning atoi() cannot distinguish invalid input from a valid zero and cannot reliably report overflow. Use strtol() when error detection is required.
💡 Tip It parses only the prefix: "12abc" produces 12, and the invalid suffix is not treated as an error.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QDoes atoi("abc") returning 0 prove that the input is invalid?
ANo, because atoi("0") also returns 0. atoi provides neither an end position nor an error state to distinguish the cases.
QWhy is strtol preferable to atoi for user input?
Astrtol reports where parsing stopped through endptr and can report range errors through errno, allowing validation of the whole input and the result range.
QDoes atoi treat a leading 0 as octal and a 0x prefix as hexadecimal?
ANo. atoi parses decimal, so the text 010 yields 10, not 8; for 0x10, it normally converts only the initial 0 and stops at x. To detect a base automatically from C prefixes, use strtol with base 0 and check where parsing ended.