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;

In this program I am trying to write records into file named, employee.dat. Program executed fine, but it will takes only one record of employee and then program gets terminated. It is not asking for next record to add i.e.,

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

are not getting executed in the program.

Thanks in advance....

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
reddy
  • 11
  • 3

3 Answers3

2

The problem that you're experiencing is that scanf("%c", &another); only grabs a single character from the input buffer. This would be fine, except that there's still a newline left in the input buffer that resulted from hitting 'enter' after your input. You need to clear the input buffer after you use getchar() like this:

char c;
while ((c = getchar()) != '\n');
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
0

You can do this:

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);

    }
One Man Crew
  • 9,420
  • 2
  • 42
  • 51
  • `flushall` is not a standard function. And in any case, trying to flush an input stream is undefined behavior. – interjay Aug 04 '13 at 14:09
0

You can fixed it simply by use : scanf("\n%c",&another); instead of scanf("%c",&another);

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

Example--->Here your input is : name_1 22 6000.000 <"Enter">

Then in the buffer : 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">
Lidong Guo
  • 2,817
  • 2
  • 19
  • 31