C语言清空缓冲区
[cpp]?view plaincopy #include?<stdio.h>?? int?main()?? {?? ????int?num;?? ????char?ch?;?? ????scanf("%d",?&num);?? ????scanf("%c",?&ch);?? ????printf("hello?world\n");?? ????system("pause");?? ????return?0;?? }??
#include?<stdio.h>?? int?main()?? {?? ????int?num;?? ????char?ch?;?? ????scanf("%d",?&num);?? ????setbuf(stdin,?NULL);//使stdin輸入流由默認緩沖區轉為無緩沖區?? ????scanf("%c",?&ch);?? ????printf("hello?world\n");?? ????system("pause");?? ????return?0;?? }??
#include?<stdio.h>?? int?main()?? {?? ????int?num;?? ????char?ch?;?? ????scanf("%d",?&num);?? ????while?((c?=?getchar())?!=?EOF?&&?c?!=?'\n');//不停地使用getchar()獲取緩沖中字符,直到獲取的c是“\n”或文件結尾符EOF為止?? ????scanf("%c",?&ch);?? ????printf("hello?world\n");?? ????system("pause");?? ????return?0;?? }??
[cpp]?view plaincopy
[cpp]?view plaincopy
注意:有很多人可能覺得使用fflush(stdin);不就能清空緩沖區了,但使用這種方法有很多不確定性。
總結
- 上一篇: 什么是C语言中的条件编译?
- 下一篇: 函数的可重入性