问候。我 我创建了一个要求输入姓名和年龄的文件,我想提取输入到文件中的年龄数,并将该数字打印在其他文件上。 我知道我可以根据有多少个名字来计算,甚至可以根据我询问信息的次数来计算,但我需要根据数字来计算我得到的年龄,在本例中是 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”,但它似乎进入了循环,因为它当我输入完信息后没有做任何事情。
最佳答案
问题出在 while
循环的 fscanf(ap,"%d",&age);
行中。这是因为您已经编写了一个字符串拳头,并且您期望读取一个 int
。
将其替换为以下代码片段,它将解决您的问题:
...
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);
...
关于c - 将结果从一个文件传递到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128840/