【发布时间】:2014-12-08 19:49:47
【问题描述】:
我无法从文件中读取结构。我对如何打印每个人的信息并计算文件中列出的平均年龄和人数感到困惑。
#include <stdio.h>
#include <string.h>
/*
The content of the file:
John
male
19
Bill
male
20
Mary
Female
20
*/
struct person
{
char name[50];
char sex;
int age;
};
int main()
{
struct person coll;
FILE *fp;
fp=fopen("person.txt","r");
if(fp==NULL)
{
printf("Cannot open");
return 1;
}
fscanf(fp,"%c %c %d",&coll.name[50],&coll.sex,&coll.age);
printf("%c",coll.name[50]);
printf("%c",coll.sex);
printf("%d",coll.age);
return 0;
}
【问题讨论】:
-
我现在无法编译,但看起来你只是在打开文件。您需要遍历(每一行)、读取值并打印(或存储)。检查这个。 tutorialspoint.com/c_standard_library/c_function_fopen.htm