我正在使用 fprintf 将用户输入的值存储在文件中。代码未按预期工作(首先,在提示“您想继续吗?Y或N:”之后,程序会自动获取一些值并继续循环。其次,它没有将用户输入的值存储到预期的文件中。更新:我可以通过在%c之前的scanf中添加空格来让程序提示使用是否继续循环,但文件admin_db.txt仍然没有正确填充。
#include<stdio.h>
typedef struct {
char str[30];
int a[10];
}UNIX;
int main()
{
UNIX admin;
char ch;
FILE *fp;
fp=fopen("admin_db.txt","w+");
while(1)
{
printf("\nEnter the name of admin : ");
scanf("%s",&admin.str);
printf("\nEnter the age of admin : ");
scanf("%d",&admin.a);
fprintf(fp,"%s%t%d",admin.str,admin.a);
printf("\nDo you want to continue ? Y or N :");
scanf("%c",&ch);
if(ch=='n' || ch=='N')
break;
}
fclose(fp);
}
输出:
Enter the name of admin : Akhil
Enter the age of admin : 23
Do you want to continue ? Y or N : //Automatically taking some value // other than n or N and continuing loop.
Enter the name of admin : sukhi
Enter the age of admin : 30
Do you want to continue ? Y or N :
Enter the name of admin :
Enter the age of admin : ^C
此外,文件 admin_db.txt 的大小为 0 字节。
最佳答案
在接受额外输入之前,您必须刷新stdin
。以下是可移植的方法:
int ch;
while (((ch = getchar()) != '\n') && (ch != EOF));
关于c - fprintf 在 C 中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103102/