扫描数据多于预定义值的数字 [英] Scanning a number having more data than predefined value
问题描述
#include<stdio.h>
main()
{
unsigned int num;
printf("enter the number:\n");
scanf("%u",&num);//4294967299 if i'm scanning more than 4G its not scanning
printf("after scanning num=%u\n",num);// 4294967295 why its giving same 4G
/* unsigned char ch;
printf("enter the character:\n");
scanf("%d",&ch);// if i/p=257 so its follow circulation
printf("after scanning ch=%d\n",ch);// 1 its okk why not in int ..
*/
}
为什么通过scanf()
扫描输入时循环不跟随,为什么在char
的情况下跟随?
Why is circulation not following while scanning input via scanf()
, why is it following in case of char
?
推荐答案
来自 this <"%u"
格式的 code>scanf(和系列)参考:
From this scanf
(and family) reference for the "%u"
format:
数字的格式与 strtoul()
预期的相同,值为 0
为 base 参数(base 由解析的第一个字符决定)
The format of the number is the same as expected by
strtoul()
with the value0
for the base argument (base is determined by the first characters parsed)
然后我们去strtoul
函数,并读取返回值:
Then we go to the strtoul
function, and read about the returned value:
成功时对应 str 内容的整数值.如果转换后的值超出对应返回类型的范围,则发生范围错误,返回ULONG_MAX
或ULLONG_MAX
.如果无法进行转换,则返回 0
.
Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, range error occurs and
ULONG_MAX
orULLONG_MAX
is returned. If no conversion can be performed,0
is returned.
由此我们可以看出,如果您为scanf
"%u"
格式输入过大的值,那么结果将是ULONG_MAX
转换为 unsigned int
.但是在sizeof(unsigned long) >的系统上,结果会有所不同.大小(无符号整数)
.有关这方面的信息,请参见下文.
From this we can see that if you enter a too large value for the scanf
"%u"
format, then the result will be ULONG_MAX
converted to unsigned int
. However the result will differ on systems where sizeof(unsigned long) > sizeof(unsigned int)
. See below for information about that.
需要注意的是,在具有 64 位 unsigned long
和 32 位 unsigned int
的平台上,该值在 unsigned 范围内有效long
不会被转换为 egUINT_MAX
,而是使用模算术转换 as详情请看这里.
It should be noted that on platforms with 64-bit unsigned long
and 32-bit unsigned int
, a value that is valid in the range of unsigned long
will not be converted to e.g. UINT_MAX
, instead it will be converted using modulo arithmetic as detailed here.
让我们取4294967299
这样的值.32 位 unsigned int
太大了,但很适合 64 位 unsigned long
.因此,对 strtoul
的调用不会返回 ULONG_MAX
,而是返回值 4294967299
.使用标准转换规则(链接到上面),这将导致 unsigned int
值为 3
.
Lets take the value like 4294967299
. It is to big to fit in a 32-bit unsigned int
, but fits very well in a 64-bit unsigned long
. Therefore the call to strtoul
will not return ULONG_MAX
, but the value 4294967299
. Using the standard conversion rules (linked to above), this will result in an unsigned int
value of 3
.
这篇关于扫描数据多于预定义值的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!