sscanf("123456789123456789123456789", "%d", &n) 是否有定义的行为? [英] Does sscanf("123456789123456789123456789", "%d", &n) have defined behavior?

查看:34
本文介绍了sscanf("123456789123456789123456789", "%d", &n) 是否有定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sscanf()scanf 家族中的其他函数被赋予一个数字序列时,其转换值超过目标整数类型的最大值,

When sscanf() or another function from the scanf family is given a sequence of digits whose converted value exceeds the maximum value of the target integer type,

  • 是否应该认为转换失败?
  • 是否定义了行为?

推荐答案

从标准,7.21.6.2p10((f)scanf,适用于全家):

From the standard, 7.21.6.2p10 ((f)scanf, applies to the whole family):

…如果这个对象没有合适的类型,或者如果转换的结果不能在对象中表示,行为是未定义的.

… If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

看起来是对 scanf 系列非常谨慎的另一个原因.strtoXX 函数具有完全定义的行为.对于过大的输入,它们返回 LONG_MAX 等,并设置 errno == ERANGE.因此,如果您需要准确的信息,请手动标记输入并使用这些函数进行转换.另一个好处:更好的错误处理.

Looks like another reason to be very cautious with the scanf family. The strtoXX functions have a fully defined behaviour. They return LONG_MAX etc. for too large input and set errno == ERANGE. So if you need exact information, tokenise the input manually and use these functions for conversion. Another benefit: better error handling.

这篇关于sscanf("123456789123456789123456789", "%d", &n) 是否有定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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