与atoi - 如何识别零和错误之间的区别? [英] atoi — how to identify the difference between zero and error?

查看:241
本文介绍了与atoi - 如何识别零和错误之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<一个href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/\">http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

在成功,函数返回转换的整数为 INT 值。
如果没有有效的转换可以执行,则返回一个零值。
如果正确的值超出重presentable值的范围,INT_MAX或INT_MIN返回。

On success, the function returns the converted integral number as an int value. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.

所以我的atoi(便便)的atoi(0)和<$之间有何不同C $ C>的atoi(0000000)

是我的可以的循环,并为您在情况下,所有零,我得到0的结果,但不是有更好的办法?

Yes I can loop and check for all zeroes in case I get 0 result, but isn't there a better way?

注意:我使用ANSI C89

推荐答案

这就是原因的atoi有一个有时被认为是不安全的。使用与strtol / strtoul将来代替。如果您有它使用 strtonum

That's one of the reasons atoi is sometimes considered unsafe. Use strtol / strtoul instead. And if you have it use strtonum.

功能的atoi 是比你想象的更危险。 POSIX 标准说:

The function atoi is more dangerous than you might think. The POSIX standard says:

如果该值不能被重新presented,行为是不确定的。

If the value cannot be represented, the behavior is undefined.

C99标准说,这也:

The C99 standard says this also:

7.20.1

功能ATOF,与atoi,蒂和环礁不必影响的价值
  上一个错误的整数EX pression错误号。如果结果的值
  不能重新presented,该行为是理解过程网络定义。

The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined.

这篇关于与atoi - 如何识别零和错误之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆