这个问题一直困扰着我。请考虑以下程序:
#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 没有额外的幻想,如缓冲