gpt4 book ai didi

c - 如何在 C 中刷新输入流?

转载 作者:太空狗 更新时间:2023-10-29 15:10:00 25 4
gpt4 key购买 nike

我无法在此处刷新 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 another='y';
struct emp {
char name[40];
int age;
float bs;
};
struct emp e;
unsigned int const BUF_SIZE = 1024;
char buf[BUF_SIZE];

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 : ");
fgets(buf, BUF_SIZE, stdin);
sscanf(buf, "%s %d %f", e.name, &e.age, &e.bs);
fwrite(&e,sizeof(e),1,fp);
printf("Add another record (Y/N)");
another=getchar();
}
fclose(fp);
return 0;
}

输出:

dev@dev-laptop:~/Documents/c++_prac/google_int_prac$ ./a.out emp.dat

Enter name,age and basic salary : deovrat 45 23
Add another record (Y/N)y

Enter name,age and basic salary : Add another record (Y/N)y

Enter name,age and basic salary : Add another record (Y/N)

最佳答案

fflush(stdin) 是未定义的行为(a)。相反,让 scanf “吃掉”换行符:

scanf("%s %d %f\n", e.name, &e.age, &e.bs);

其他人都很好地指出 scanf 是一个糟糕的选择。相反,您应该使用 fgetssscanf:

const unsigned int BUF_SIZE = 1024;
char buf[BUF_SIZE];
fgets(buf, BUF_SIZE, stdin);
sscanf(buf, "%s %d %f", e.name, &e.age, &e.bs);

(a) 例如,参见 C11 7.21.5.2 fflush 函数:

int fflush(FILE *stream) - If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

关于c - 如何在 C 中刷新输入流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1384073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com