C语言 为什么多个“”字符最终不会出现在标准输入流中



这个问题一直困扰着我。请考虑以下程序:

#include <stdlib.h>
#include <stdio.h>
int main(void){
  char one,mid,final;
  int num;
  printf("Enter the first character:n");
  scanf("%c",&one);
  printf("Enter any integer:n");
  scanf("%d",&num);
  printf("Enter the middle character:n");
  scanf("%c",&mid);
  printf("Enter the final character:n");
  scanf("%c",&final);
  printf("You have enteredn");
  printf(""%c" and "%d" and "%c" and "%c"n",one,num,mid,final);
  return EXIT_SUCCESS;
}

假设输入是

An
34n
Bn

这里

第一个scanf A并将n留在stdin中。
第二个不伴随n,因为%d跳过它们,因此得到 34。这个scanf也留下了n字符在stdin
第 3 个scanf得到第二个scanf剩余的n
第 4 scanf B,再次将n留在stdin中。

我的问题是:为什么最后一个scanf不消耗第一个scanf留下的n字符?

跳过

的字符不会在流中"左"。输入流只能沿一个方向读取一次,1 因此一旦跳过字符,它就会消失。

1 没有额外的幻想,如缓冲

最新更新