c - fprintf 在 C 中的使用

标签 c file-io struct

我正在使用 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/

相关文章:

c - C中退出代码11的含义?

c++ - 是否显示Common Item Dialog 或GetOpenFileName? (Win32 API)

c++ - 为什么打印浮点值时出现字符 'e'

c - 访问结构体内部的数组

c - 如何使一个字段指向它的结构?

C静态变量

c++ - 如何加速 ifstream 转换为 float

matlab - 将文本中的wordS 替换为wordS,然后将其保存到新文件中。 MATLAB

Java vs C# 多线程性能,为什么 Java 变慢了? (包括图表和完整代码)

c - 通过将结构体的地址获取到其他类型的结构体的指针来获取临时[-fpermissive]的地址