有什么scanf函数之间的差异(QUOT;%D")和scanf(QUOT;%D")?
#include <stdio.h>
int main(void)
{
int i, j;
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d \n", j);
printf("enter a value for i ");
scanf("%d",&i);
printf("i is %d \n", i);
return 0;
}
如何在 scanf()的
函数实际上,当我的格式说明像 scanf函数(%D之后添加空格,与放工作;Ĵ );
How does the scanf()
function actually work when I add spaces after the format specifier like scanf("%d ",&j);
?
在scanf格式空格字符,使其明确地阅读,而忽略尽可能多的空白字符,因为它可以。因此,与 scanf函数(%d个,...
,读了许多之后,它将继续读取字符,丢弃所有空白,直到它看到一个非空白字符输入,即非空白字符将被留作为下一个字符由一个的输入功能来读取。
A whitespace character in a scanf format causes it to explicitly read and ignore as many whitespace characters as it can. So with scanf("%d ", ...
, after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input. That non-whitespace character will be left as the next character to be read by an input function.
通过您的code:
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d \n", j);
将打印的第一行,然后等待你输入一个数字,然后的后继续的数量要等待的东西。所以,如果你只需要输入 5 骨节病> 输入骨节病>,它会出现挂 - 你需要输入一些非空白字符它继续另一条线。如果然后键入 6 骨节病> 输入骨节病>,这将成为 i的值
,让你的屏幕看起来是这样的:
it will print the first line and then wait for you to enter a number, and then continue to wait for something after the number. So if you just type 5Enter, it will appear to hang — you need to type in another line with some non-whitespace character on it to continue. If you then type 6Enter, that will become the value for i
, so your screen will look something like:
enter a value for j 5
6
j is 5
enter a value for i i is 6
此外,由于大多数scanf函数%-conversions也跳过前导空白(所有除了%C
,%[
和%N
),空格的前的%-conversions是无关的(%D
和%D
将相同的行为)。因此,在大多数情况下,你应该避免在scanf中的转换空间,除非你知道你特别需要他们的奇特效果。
Also, since most scanf %-conversions also skip leading whitespace (all except for %c
, %[
and %n
), spaces before %-conversions are irrelevant ("%d"
and " %d"
will act identically). So for the most part, you should avoid spaces in scanf conversions unless you know you specifically need them for their peculiar effect.