C语言清空输入缓冲区在标准输入(stdin)情况下的使用
程序1:
//功能:先输入一个数字,再输入一个字符,输出hello bit#include <stdio.h>int main(){int num = 0;char ch = ' ';scanf("%d", &num);scanf("%c", &ch);printf("hello bit\n");system("pause");return 0;}
结果:
7
hello bit
请按任意键继续. . .
分析:并没有输入字符,直接就输出了“hello bit”,因为在点击回车(‘\n’)时,相当于输入了一个字符,那么我们需要进行清空缓冲区处理
程序2:
#include <stdio.h>int main(){int num = 0;char ch = ' ';scanf("%d", &num);/*fflush(stdin);*/ //清空缓冲区时容易出错,不建议使用/*scanf("%*[^\n]");*///也不好用,容易失效 setbuf(stdin, NULL);//使stdin输入流由默认缓冲区转为无缓冲区,可以用scanf("%c", &ch);printf("hello bit\n");system("pause");return 0;}
结果:
5
j
hello bit
请按任意键继续. . .
程序3:
//功能:先输入一个数字,再输入一个字符,输出hello bit#include <stdio.h>#define CLEAR_BUF() \int c = 0; \while ((c = getchar()) != EOF && c != '\n')\{ \ ; \}int main(){int num = 0;char ch = ' ';scanf("%d", &num);CLEAR_BUF();scanf("%c", &ch);printf("hello bit\n");system("pause");return 0;}
结果:
8
s
hello bit
请按任意键继续. . .
分析:程序3建议使用,不停地使用getchar()获取缓冲中字符,直到获取的C是“\n”或文件结尾符EOF为止,此方法可完美清除输入缓冲区,并具备可移植性