使用%3d时的意外输出(scanf()中的最大字段宽度说明符)

时间:2017-10-04 18:26:17

标签: c scanf

源代码:

#include <stdio.h>
main()
{
    int a,b,c;
    printf("Enter: ");
    scanf("%3d %3d %3d",&a,&b,&c);
    printf("%d",b);
}

输出:

Enter: 1234 5678 9
4
--------------------------------
Process exited after 7.322 seconds with return value 1
Press any key to continue . . .

当我在这里使用scanf("%3d %3d %3d",&a,&b,&c);时,为什么b得到值4而不是456?

使用%3d %3d %3d应该提取(三次)三个连续的非空白字符,并将它们分别放在变量abc中,不是吗?

1 个答案:

答案 0 :(得分:1)

由于@SouravGosh指出% n d其中n是数字格式,指定要作为此字段的一部分读取的最大字符数。

所以你输入&#34;1234␣567␣8&#34;,消费123; b因␣而消耗4并停止;然后c消耗567。