1
int main()
{

    FILE *fp;
    char another = 'Y';
    struct emp
    {
            char name[20];
            int age;
            float bs;
    };
    struct emp e;

    fp = fopen("employee.dat", "w");

    if(fp == NULL)
    {
            printf("file cannot be opened for writing\n");
            exit(1);
    }

    while(another == 'Y')
    {
            printf("\n enter name, age and basic salary: ");
            scanf("%s %d %f", e.name, &e.age, &e.bs);
            fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);

            printf(" Add another record (Y/N)");
            fflush(stdin);
            scanf("%c", &another);
    }

    fclose(fp);
    return 0;

在这个程序中,我试图将记录写入名为employee.dat 的文件中。程序执行得很好,但只需要一条员工记录,然后程序就会终止。它不要求添加下一条记录,即

 fflush(stdin); 
 scanf("%c", &another);

没有在程序中执行。

提前致谢....

4

3 回答 3

2

您遇到的问题是scanf("%c", &another);只从输入缓冲区中抓取一个字符。这很好,只是输入缓冲区中仍然有一个换行符,这是在您输入后点击“输入”导致的。使用后需要清除输入缓冲区getchar()

char c;
while ((c = getchar()) != '\n');
于 2013-08-04T13:38:32.203 回答
0

您可以简单地通过使用来修复它:scanf("\n%c",&another);而不是scanf("%c",&another);

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

示例--->这里您的输入是:name_1 22 6000.000 <"Enter">

然后在缓冲区中:name_1 -->e.name 22-->e.age 6000.00-->e.bs <"Enter">-->nothing

fflush(stdin);//it didn't delete the <"Enter">.
scanf("\n%c", &another);//here we deal with <"Enter">
于 2013-08-04T14:44:02.113 回答
0

你可以这样做:

while(another == 'Y' || another == 'y')
    {
            printf("\n enter name, age and basic salary: ");
            scanf("%s %d %f", e.name, &e.age, &e.bs);
            fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);

            printf(" Add another record (Y/N)");

            another=getch();
            //scanf("%c", &another);

    }
于 2013-08-04T14:00:08.713 回答