【发布时间】:2019-12-08 17:50:23
【问题描述】:
我正在读取格式如下的文本文件:
名字 姓 年龄 NumberOfSiblings 母亲父亲
导入头文件:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
结构体定义如下:
typedef struct {
int person_ID; //not included in file
char full_name[20];
char sex[2];
char countryOfOrigin[20];
int num_siblings;
float parentsAges[2]; //this should store mother and fathers age in an array of type float
} PersonalInfo;
void viewAllPersonalInformation(){
FILE* file = fopen("People.txt", "r");
if (file == NULL){
printf("File does not exist");
return;
}
int fileIsRead = 0;
int idCounter = 0;
PersonalInfo People[1000];
//headers
printf("%2s |%20s |%2s |%10s |%2s |%3s |%3s\n", "ID", "Name", "Sex", "Born In", "Number of siblings", "Mother's age", "Father's Age");
do{
fileIsRead = fscanf(file, "%s %s %s %d %f %f\n", People[idCounter].full_name, People[idCounter].sex, People[idCounter].countryOfOrigin, &People[idCounter].num_siblings, &People[idCounter].parentsAges[0], &People[idCounter].parentsAges[1]);
People[idCounter].person_ID = idCounter;
printf("%d %s %s %s %d %f %f\n", People[idCounter].person_ID, People[idCounter].full_name, People[idCounter].sex, People[idCounter].countryOfOrigin, People[idCounter].num_siblings, People[idCounter].parentsAges[0], People[idCounter].parentsAges[1]);
idCounter++;
}
while(fileIsRead != EOF);
fclose(file);
printf("Finished reading file");
}
int main() {
viewAllPersonalInformation();
return 0;
}
People.txt 的样子:
约翰·奥唐纳 F 爱尔兰 3 32.5 36.1
玛丽·麦克马洪 M 英格兰 0 70 75
彼得汤普森 F 美国 2 51 60
【问题讨论】:
-
你能分享一个最小的例子吗?
-
你传递给
fscanf的指针是从未初始化的内存中读取的。 -
@gsamaras 抱歉,我没有完全理解一个最小的例子?我需要遍历文件,将数据分配给结构并打印。我尝试使用 fscanf 来获取值并使用 printf 来打印它们。不确定要省略什么?
-
@user2363025 一个完整的最小示例,包含您的主结构、结构、在读取数据之前为指针分配内存的方式以及读取数据的方式。根据您现在的问题,可以得出您忘记为指针分配内存的结论。是这样吗?一个完整的最小示例将毫无疑问,并且不需要假设;)
-
@gsamaras 你确实跳到了正确的方向:) 我需要动态创建内存,但作为一个起点,我已经修改了结构,以便全名和国家/地区是固定长度 20 和浮动数组是固定长度 2。但程序仍然在 fileread 行崩溃
标签: c arrays string struct typedef