将数据放入文件中

时间:2018-07-10 04:50:33

标签: c scanf

int main()
{
 FILE*arq;
 char a[500];
  int i,f;
  arq=fopen("test.txt","w+");
 for(i=0;i<5;i++){
  printf("Type the name:");
  fgets(a,500,stdin);
  fprintf(arq,"%s",a);
  printf("Enter the age");
  fscanf(arq,"%d", f);
  fprintf(arq, "%d", f);
 }
fclose(arq);
return 0;
}

我无法在文件中输入名称和年龄,因为键入名称后,它将跳过年龄的输入

3 个答案:

答案 0 :(得分:0)

调用fscanf()时,您未能传递指向将保存结果的变量的指针。应该是:

fscanf(arq, "%d", &f);

&告诉编译器您要传递f的地址而不是f的值。这是必要的,因为fscanf的最后一个参数是您想要存储结果的地址。

答案 1 :(得分:0)

您需要提供要填充的变量的地址。

fscanf(arq,"%d", f);

->

fscanf(arq,"%d", &f);

首先,读取a并不是必需的,因为它是一个数组,无论如何它都会被视为指针。

答案 2 :(得分:0)

首先,您必须提供要填充的变量的地址。其次,您正在读取文件,该文件在您关闭之前为空,因此不会等待来自stdin的输入。应该是这样的:

fscanf(stdin,"%d", &f);

这将在缓冲区中保留一个'\ n',它将被fgets读取。为防止这种情况,请在下一次迭代之前阅读换行符:

fgetc(stdin);

此代码对我有用:

int main()
{
 FILE*arq;
 char a[500];
 int i,f;
 arq=fopen("test.txt","w+");

 for(i=0;i<5;i++){
  printf("Type the name:");
  fgets(a,500,stdin);
  fprintf(arq,"%s",a);
  printf("Enter the age:");
  fscanf(stdin,"%d", &f);
  fprintf(arq, "%d", f);
  fgetc(stdin);
 }
 fclose(arq);
 return 0;
}