为什么只有一个(两个中的)空格被视为输入缓冲区中的字符?

Why only one (out of two) whitespace was considered as character in the input buffer?

我正在尝试了解输入缓冲区的工作原理。于是写了一段代码:

    #include<stdio.h>
    int main(){
    int a,b;
    char c,d;
    scanf("%d %d",&a,&b);
    scanf("%c %c",&c,&d);
    printf("%d*%d*%c*%c",a,b,c,d);
    return 0;
    }

现在输入:

    5 4 qw

所以我期望我的输出是:

    5*4* *

输出:

    5*4* *q

有人能解释一下为什么它只考虑两个空格中的一个(一个在 5 和 4 之间,另一个在 4 和 q 之间)作为一个字符,而不是两个?两个空格中的哪一个被打印为一个字符?

如果我们从

开始
scanf("%d %d",&a,&b);

然后将读取 54,将输入缓冲区保留为 " qw"

现在当你这样做时

scanf("%c %c",&c,&d);

第一个 "%c" 读取 space,而另一个读取 'q''w' 将留在输入缓冲区中。

这是因为"%c"格式没有跳过white-space。它将读取输入缓冲区中的 any 个字符。

如果您阅读例如this scanf (and family) reference 您会看到 "%c""%[""%n" 格式不会 丢弃前导白色-space。

对于 %dscanf 查找数字并忽略 space,但是对于 %cq 之前的 space 是没有被忽略。

考虑

scanf("%d %d%c %c",&a,&b,&c,&d);
// input "5 4 qw"

"%d":reads/discards前导白space(有none)然后reads/saves为int'5' -> 5.
" " : reads/discards 白色space (1 space: ' ').
"%d": reads/discards leading whitespace (有none)然后reads/saves as int '4' -> 4.
"%c": reads/saves 1个字符 , space ' '.
" " : reads/discards 白space (有none).
"%c": reads/saves 1个字符,'q'

'w' 保留在 stdin.


如果代码未通过 "%c" 读取 white-spaces,请在说明符前加上 space。还要检查 return 值。

//              v
if (scanf("%d %d %c %c",&a,&b,&c,&d) == 4) Oh_Happy_Day();