【问题标题】:fprintf use in C [duplicate]C中的fprintf使用[重复]
【发布时间】: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 (是的想继续)程序正在退出。

标签: c file-io struct


【解决方案1】:

您必须先刷新stdin,然后才能获取其他输入。以下是可移植的方法:

int ch;
while (((ch = getchar()) != '\n') && (ch != EOF));

【讨论】:

  • 为此ch 必须是int(OP 已将ch 声明为char)。
  • @Kninnug:谢谢。更新了我的答案。 :)
  • 不工作,即使我输入 Y 或 y 仍然退出。同样在进入循环之前,编译器正在等待用户输入值以执行循环,如果你按下回车它就会退出(因为你的代码逻辑 '\n' )
  • 答案如下:#include typedef struct { char str[40];整数 [5] ; }UNIX; int main() { 文件 *fp;字符 ch='y'; UNIX 管理员; fp=fopen("/home/akhils/file_dir/admin_db.data","a");诠释我=0; while(1) { printf("请输入管理员名称:"); scanf("%s[^\n]",admin.str); printf("\n请输入管理员年龄:"); scanf("%d[^\n]",admin.a); printf("\n你要继续吗?Y还是N:"); scanf("%c",&ch); fprintf(fp,"%s \t %d\n",admin.str,admin.a[0]);我++; if(ch=='N' || ch=='n') 中断; } fclose(fp); }
猜你喜欢
  • 2023-04-09
  • 2011-10-31
  • 2017-11-08
  • 2014-01-19
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2019-04-28
  • 2018-04-11
相关资源
最近更新 更多