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);
未在程序中执行。
提前致谢....
答案 0 :(得分:2)
您遇到的问题是scanf("%c", &another);
只从输入缓冲区中抓取一个字符。这样就可以了,除了输入缓冲区中仍然有一个新行,因为在输入后点击“输入”。使用getchar()
后,您需要清除输入缓冲区:
char c;
while ((c = getchar()) != '\n');
答案 1 :(得分: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);
}
答案 2 :(得分: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”> - >没有
fflush(stdin);//it didn't delete the <"Enter">.
scanf("\n%c", &another);//here we deal with <"Enter">