scanf()无法检测到错误输入
int i, f;
f = scanf("%d", &i);
当我输入以 33333333333333333333333
(大于 int
的容量)时,输入输入。 f
的值不应该为 0
吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
int i, f;
f = scanf("%d", &i);
当我输入以 33333333333333333333333
(大于 int
的容量)时,输入输入。 f
的值不应该为 0
吗?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
使用标准C,没有。使用
scanf(“%d”,& i)
,int
溢出,结果为 undfeined 。使用
scanf()
in unix (哪个(哪个)有变化),我发现没有预防溢出的不确定行为。最好抛弃(不使用)
scanf()
并使用fgets()
用于所有用户输入。代码可以尝试文本宽度限制和更广泛的类型:
然而,在
int
的新颖实现上却有困难,宽度与intmax_t
一样宽。scanf()
返回0时找到int
找到的文本输入。OP的问题中缺少的关键设计元素是超过
int
范围的用户输入应该发生什么?第一个“ 333333333”之后停止阅读?什么是最佳,取决于OP想要如何详细处理错误条件 - 尚未说明的事情。
With standard C, no. With
scanf("%d",&i)
, onint
overflow, the result is undefined.With
scanf()
in Unix (of which there are variations), I find no prevention of undefined behavior with overflow.Best to ditch (not use)
scanf()
and usefgets()
for all user input.Code could try a textual width limit and a wider type:
Yet that has trouble on novel implementations where
int
is as wide asintmax_t
.scanf()
returns 0 when noint
textual input found.A key design element missing from OP's questions is what should happen to user input that exceeds the
int
range? Stop reading after the first `"333333333"?What is best, depends on how OP wants to handle, in detail, error conditions - something not yet stated.
不,无法以这种方式检测到。
以下不是便携式解决方案,但它在 gcc 12.1, clang 14.0和 msvc 19.32。它可能停止在以后的版本中工作。
您需要首先设置
errno = 0;
,然后检查范围错误:对于可移植性,请从 C2X标准的早期草稿:
一个更好的(如 portable 中)检测到的选项是首先阅读到
char []
buffer,然后使用strtol()
将其转换为数字。从相同的标准草稿中:这是一个使用
strtol()
(转换为long
)的例证程序:可能的输出:
No, it can't be detected that way.
The below is not a portable solution, but it works in gcc12.1, clang14.0 and msvc19.32. It may stop working in later releases.
You need to set
errno = 0;
first and then check it for range errors:For portability, read this from an early draft of the C2x standard:
A better (as in portable) option to detect this would be to read into a
char[]
buffer first and then usestrtol()
to convert it to a number. From the same standard draft:Here's a demonstrative program using
strtol()
(which converts tolong
):Possible output:
scanf(“%d”,& i)
不会检测到溢出,甚至更糟,scanf()
如果数字超过目标类型的范围:根据实现的不同,i
的值可以是-434809515
,-1
,0
0 ,int_max
或任何值,包括带有或没有某些不良副作用的陷阱值。检查输入的正确方法是将其读取为
char
数组中的一行,并用strtol()
:您可以将这些测试封装在<<<代码> getint()函数:
scanf("%d", &i)
does not detect overflow, worse even,scanf()
has undefined behavior if the number exceeds the range of the destination type: depending on the implementation, the value ofi
could be-434809515
,-1
,0
,INT_MAX
or any value including a trap value with or without some undesirable side effects.The proper way to check the input is to read it as a line in an array of
char
and to parse it withstrtol()
:You can encapsulate these tests in a
getint()
function: