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

标签 c io stream stdio

我无法在此处刷新 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/

相关文章:

c++ - c 中不兼容的指针类型警告?

c - 为什么这个片段给出 6 作为输出?

c - 如何从输入中正确扫描一行并写入输出文件

iPhone:使用 NSStream 捕获连接错误

stream - GNURADIO 3.7.8 : identify a part of a byte stream

.net - 有没有办法在 dotnet 中使用 AWSSDK 逐 block 获取 s3 对象流?

python - 将 C 函数的指针参数与 python 脚本中的 ctype 参数链接起来

haskell - 如何构建 IO 的 Haskell 代码?

linux - "sort < output"和 "sort output"之间的区别

c - C语言中函数有存储类吗?