Detecting integral overflow with scanf

家住魔仙堡 提交于 2019-11-29 01:46:03

The only portable way is to specify a field width, e.g. with "%4d" (guaranteed to even fit into a 16-bit int) or by building up the format string at run-time with a field width of (int)(log(INT_MAX) / log(10)). This of course also rejects for example 32000, although it would fit into a 16-bit int. So no, there is no satisfying portable way.

POSIX don't specify more here, nor mention ERANGE.

This manpage mentions setting errno only in case EOF is returned; the glibc documentation doesn't mention ERANGE at all.

That leaves the question what to suggest to beginners for reading integers, where I have no idea. scanf has too many undefined and underspecified aspects to be really useful, fgets cannot be used in productive code because you cannot handle 0-bytes properly, and portable error checking with strtol and friends takes more lines than implementing the functionality yourself (and is quite easy to get wrong). The behaviour of atoi is also undefined for integer overflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!