【问题标题】:Passing a result from a file to another file将结果从文件传递到另一个文件
【发布时间】:2018-05-02 07:02:40
【问题描述】:

问候。一世 我创建了一个询问姓名和年龄的文件,我想提取输入到文件中的年龄数,并将该数字打印在其他文件上。 我知道我可以根据有多少名字,甚至是我询问信息的次数来计算,但我需要根据数字来计算我得到了多少年龄,在这种情况下 int,并将其打印在其他文件上。 这是我的代码:

#define T 50
#define A 5
void main ()
{
   FILE *ap=NULL, *ap2=NULL;
   char cad[T];
   int age, x,cont=0;

   ap=fopen("Dat.txt", "w+"); //Open File
   if(ap==NULL)
   {  printf("Cant open the file");
      getch();
      exit(1);
   }
   ap2=fopen("Ages.txt","w"); //Open File
   if(ap2==NULL)
   {  printf("Cant open the file");
      getch();
      exit(1);
   }
   for(x=0;x<A;x++) //Gets the information
   {  printf("Name: ");
      gets(cad);
      printf("Age: ");
      scanf("%d",&age);
      fflush(stdin);
      fprintf(ap,"%-30s %d\n",cad,age);
   }
   rewind(ap);
   fgets(cad,T,ap);
   while(!feof(ap))     //Start counting the ages
   {  fscanf(ap,"%d",&age);
      ++cont;
   }
   fprintf(ap2,"%d", cont);

   fclose(ap); fclose(ap2); //Close both Files

如果我注释最后 6 行代码(fclose 除外),它可以很好地创建包含所有信息的文件“Dat.txt”,但它似乎进入了一个循环,因为它输入完信息后什么都不做。

【问题讨论】:

  • 我不明白你的问题,但我觉得它与Why is “while ( !feof (file) )” always wrong? 有关——除此之外,never use gets()!
  • 我应该创建一个文件,在本例中是“Dat.txt”,它有很多我想要的名称和年龄,因为代码可以创建该文件。我需要再读一遍(这就是我使用 w+ 的原因),并根据我在阅读时获得的年龄数,我将创建一个名为“Ages.txt”的新文件,其中包含年龄数我数了数。
  • 如果您测试了fscanf 的返回值,很明显:fscanf(ap,"%d",&amp;age); 返回 0,因为它正在尝试读取名称并且无法将其解码为 int。而fflush(stdin) 是非标准的,只是微软的扩展。它不会用 gcc 或 clang 清理输入流...
  • 我使用 'fflush(stdin)' 因为当我写完年龄时,会在 'for' 循环中自动询问我的下一个年龄,似乎 '\n' 正在进入细绳。它让我对'fscanf'感到困惑,因为我想在阅读文件时单独打印年龄,但我不知道如何。我试图用'puts(cad)'打印字符串,我注意到字符串是随着年龄而来的......所以不知道该怎么做

标签: c file


【解决方案1】:

问题在fscanf(ap,"%d",&amp;age); ofwhile 循环中。这是因为你已经写了一个字符串拳头并且你期望读到一个int

将其替换为以下代码 sn-p 即可解决您的问题:

...
rewind(ap);
fgets(cad,T,ap);
while(!feof(ap))     //Start counting the ages
{
   //Move pointer to 30, Since while writing to file width is set to 30(%-30s) 
   age = atoi(cad+30); 
   printf("%d\n",age);
   ++cont;
   fgets(cad,T, ap);
}
fprintf(ap2,"%d", cont);
...

【讨论】:

  • 谢谢,这对我的循环有帮助,但我仍然很困惑,如果我在 fscanf 之后使用 puts(cad); While循环,我看到打印带有年龄的名称,如果我尝试单独打印该数字,使用 printf("Age: %d\n",age) 它会打印最后一个年龄在乞讨登记。有什么方法可以将年龄与文件分开打印?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
  • 1970-01-01
相关资源
最近更新 更多