2013-08-04 62 views
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; 

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

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

没有在程序中执行。

在此先感谢....

回答

1

的问题,你遇到的是只scanf("%c", &another);抓住从输入缓冲器中的单个字符。这很好,除了输入缓冲区中还有一个换行符因输入后点击'enter'而产生。你需要清空输入缓冲区使用getchar()后是这样的:

char c; 
while ((c = getchar()) != '\n'); 
+0

没有必要! noly使用flushall(); scanf后 –

+0

@OneManCrew你是什么意思“不需要”?这是另一种方式,与您的一样好。 –

1

你可以这样做:

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

    } 
+0

'flushall'不是一个标准功能。在任何情况下,尝试刷新输入流都是未定义的行为。 – interjay

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 < “输入”> - >没什么

fflush(stdin);//it didn't delete the <"Enter">. 
scanf("\n%c", &another);//here we deal with <"Enter">