繁体   English   中英

将数据放入文件中

[英]Putting data in files with for

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;
}

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

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

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

&告诉你想的地址通过编译器f ,而不是价值f 这是必需的,因为fscanf的最后一个参数是您要将结果存储在其中的地址。

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

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

->

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

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

首先,您必须提供要填充的变量的地址。 其次,您正在读取文件,该文件在您关闭之前为空,因此不会等待来自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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM