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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

int atoi(const char *nptr);

⚙️ Parameters

nptr RequiredA 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏