[英]variations in scanf in C language
scanf("%d %d"+2, &a, &b);
printf("%d\n%d", a, b);
It accepts only a
and prints a
and 0
.它只接受a
并打印a
和0
。
Can anyone explain why this is happening?谁能解释为什么会这样? Also, if I write +1
instead of +2
, it accepts nothing and prints 0
and 0
.另外,如果我写+1
而不是+2
,它不接受任何内容并打印0
和0
。
This:这个:
scanf("%d %d"+2,&a,&b);
is the same as是相同的
scanf(" %d", &a, &b);
which is the same as这与
scanf("%d", &a, &b);
which means that the extra &b
argument is unnecessary.这意味着额外的&b
参数是不必要的。
What happens here is that "%d %d"
is a char*
.这里发生的是"%d %d"
是一个char*
。 Adding two to it results into a pointer pointing two bytes ahead which means that it now points to " %d"
.将两个添加到它会产生一个指向前面两个字节的指针,这意味着它现在指向" %d"
。 The leading space is unnecessary because %d
already skips leading whitespace characters.前导空格是不必要的,因为%d
已经跳过前导空格字符。
When you use +1
instead of +2
, the scanf
is the same as当您使用+1
而不是+2
, scanf
与
scanf("d %d", &a, &b);
which means that it expects a d
in the input followed by an integer to be assigned to a
.这意味着它期望输入中的d
后跟一个整数分配给a
。 Since you provide a number instead of d
in the input, the scanf
fails and returns 0. Thus, nothing is accepted and the execution reaches the printf
which prints the value of both a
and b
.由于您在输入中提供了一个数字而不是d
,因此scanf
失败并返回 0。因此,没有任何东西被接受并且执行到达printf
,它打印了a
和b
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.