刷新输入流C的问题

deo*_*ngh 5 c stream

我无法在这里刷新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 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;
}

output for this is :-

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)

And*_*ton 10

fflush(stdin)是未定义的行为(a).相反,让scanf"吃"新线:

scanf("%s %d %f\n", e.name, &e.age, &e.bs);
Run Code Online (Sandbox Code Playgroud)

其他人都很擅长做出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);
Run Code Online (Sandbox Code Playgroud)

(a)例如,见C11 7.21.5.2 The fflush function:

int fflush(FILE *stream)- 如果指向输入流或未输入最近操作的更新流,则fflush功能会将该流的任何未写入数据传送到主机环境以写入该文件; 否则,行为未定义.


Rob*_*nes 8

更新:您需要在循环结束时添加另一个getchar()以使用Y/N后面的'\n'.我不认为这是最好的方法,但它会让你的代码现在正常运作.

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();
    getchar();
}
Run Code Online (Sandbox Code Playgroud)

我建议将要解析的数据(最多包括'\n')读入缓冲区,然后使用sscanf()解析出来.这样您就可以使用换行符,并且可以对数据执行其他健全性检查.

  • fflush()用于标准I/O流 - 你的意思是什么?您不将它用于输入文件 - 它旨在刷新缓冲输出.但那不是你说的.使用fflush(stdout)是好的 - 甚至是明智的; 特别是在调试模式下.(使用fflush(0)可能更明智,但这又是一个稍微不同的问题.) (2认同)