【发布时间】:2015-08-19 18:34:29
【问题描述】:
我正在使用 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 字节。
【问题讨论】:
-
%t不是有效的fprintf说明符(据我所知),您的意思是\t? -
多次重复。
scanf()将换行符留在输入缓冲区中;scanf("%c", …)抓住换行符。在%c:scanf(" %c", &ch);` 前面放置一个空格以跳过空格。每次检查来自scanf()的返回值。如果不是您期望的值的数量(代码中的 1),那就有问题了。 -
@Kninnug 你是对的,我的意思是 \t ,无论如何情况都是一样的。
-
选择了错误(或不是最佳)副本。建议改为SO 217074。
-
@JonathanLeffler 我现在在 scanf 中的 %c 之前放了空格,它现在提示用户输入一个值并等待输入,但即使我输入 y (是的想继续)程序正在退出。