程序不会在scanf("%c",&ch)行停止.为什么它会发生sombody可以请向我解释这个
#include#include struct list { char val; struct list * next; }; typedef struct list item; void main() { char ch; int num; printf("Enter [1] if you want to use linked list or [2] for realloc\n"); scanf("%d", &num); if(num == 2) { scanf("%c", &ch); printf("%c", ch); } }
Paul92.. 15
假设您在读取num时输入2.实际输入流将是2 \n(\n是换行符).2进入num,并且仍然是\n,进入ch.要避免这种情况,请在格式说明符中添加空格.
scanf(" %c", &ch);
这将忽略任何空格,换行符或制表符.
假设您在读取num时输入2.实际输入流将是2 \n(\n是换行符).2进入num,并且仍然是\n,进入ch.要避免这种情况,请在格式说明符中添加空格.
scanf(" %c", &ch);
这将忽略任何空格,换行符或制表符.
这背后的原因是\n
前一个scanf
按下Enter键时留下的换行符,用于下一次读取scanf
.当声明
scanf("%c", &ch);
执行然后它读取前一个\n
留下的scanf
.
要吃掉它,\n
你可以在%c
说明符之前使用空格.%c
说明符之前的空格可以占用任意数量的空白字符.
scanf(" %c", &ch); ^ a space