因此,谷歌快速搜索fflush(stdin)清除输入缓冲区会发现许多网站警告不要使用它.然而,这正是我的CS教授教授课程的原因.
使用有多糟糕fflush(stdin)?即使我的教授正在使用它并且似乎完美无缺地工作,我是否真的应该放弃使用它?
我无法在这里刷新stdin,有没有办法刷新stdin?如果没有,那么如何让getchar()从用户输入一个字符作为输入,而不是输入缓冲区中scanf留下的"\n"? ?
#include "stdio.h"
#include "stdlib.h"
int main(int argc,char*argv[]) {
FILE *fp;
char another='y';
struct emp {
char name[40];
int age;
float bs;
};
struct emp e;
if(argc!=2) {
printf("please write 1 target file name\n");
}
fp=fopen(argv[1],"wb");
if(fp==NULL) {
puts("cannot open file");
exit(1);
}
while(another=='y') {
printf("\nEnter name,age and basic salary");
scanf("%s %d %f",e.name,&e.age,&e.bs);
fwrite(&e,sizeof(e),1,fp);
printf("Add another record (Y/N)");
fflush(stdin);
another=getchar();
}
fclose(fp);
return 0;
}
编辑: - 更新的代码,仍然无法正常工作
#include "stdio.h"
#include "stdlib.h"
int main(int argc,char*argv[]) {
FILE *fp;
char …