atoi() – 字符串到int

我读到atoi()已被弃用,它相当于:

 (int)strtol(token_start, (char **)NULL, 10); 

这是否意味着我应该使用上面而不是atoi(chr)或者它只是说它们是等价的?

它确实在Apple的Mac OS X手册页上为atoi(3) (以及在BSD手册页中)说过atoi已被弃用。

atoi()函数已被strtol()弃用,不应在新代码中使用。

因为这个原因,我会使用strtol()等效,但我怀疑你必须担心atoi()被删除。

来自http://www.codecogs.com/library/computing/c/stdlib.h/atoi.php实施说明

 * The atoi function is not thread-safe and also not async-cancel safe. * The atoi function has been deprecated by strtol and should not be used in new code. 

atoi不被弃用,你的来源不正确。 当前的C标准ISO 9899:2011中没有任何内容表明这一点(例如参见第6.11章未来语言方向),也没有早期标准中的任何内容。

根据C标准,atoi相当于strtol如下,C11 7.22.1.2:

atoi,atol和atoll函数分别将nptr指向的字符串的初始部分转换为int,long int和long long int表示。

除了出错的行为,它们相当于

atoi: (int)strtol(nptr, (char **)NULL, 10)

atol: strtol(nptr, (char **)NULL, 10)

atoll: strtoll(nptr, (char **)NULL, 10)

strtol是首选,因为atoi在出错时调用未定义的行为。 请参见7.22.1“如果无法表示结果的值,则行为未定义。”

atoi()的描述与strtol()的相似/差异有一个非常重要的观点。

> ... The call atoi(str) shall be equivalent to:
> (int) strtol(str, (char **)NULL, 10)
> except that the handling of errors may differ.

试试这个很有趣:

 const char *buf = "forty two"; int t1 = atoi(buf); /* detect errors? */ int t2 = strtol(buf, NULL, 10); /* detect errors? */ 

不,你不应该使用上面而不是atoi

您应该实际检查strtol提供的错误信息:

 i = atoi(s); 

应该被替换

 char* stopped; i = (int)strtol(s, &stopped, 10); if (*stopped) { /* handle error */ } 

这意味着在某个时间点atoi将不再可用。 所以现在开始更改代码