这个问题一直困扰着我。考虑以下程序:
#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 entered\n");
printf("\"%c\" and \"%d\" and \"%c\" and \"%c\"\n",one,num,mid,final);
return EXIT_SUCCESS;
}
假设输入是
A\n
34\n
B\n
这里,
第一个 scanf
获取 A
并将 \n
保留在 stdin
中。
第二个nd不使用\n
,因为%d
跳过它们,因此得到34。这个scanf
还将 \n
字符保留在 stdin
中。
第三个rd scanf
获取第二个scanf
留下的\n
。
第 4 个th scanf
获取 B
并再次将 \n
保留在 stdin
中>.
我的问题是:为什么最后一个 scanf
不消耗第一个 scanf
留下的 \n
字符?
最佳答案
跳过的字符不在流中“左侧”。输入流只能在一个方向上读取一次,1,因此一旦跳过一个字符,它就会消失。
1 没有额外的花哨,例如缓冲
关于c - 为什么标准输入流中没有出现多个 `\n` 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27924996/