【发布时间】:2021-04-17 02:13:00
【问题描述】:
以下代码读取 .txt 文件的内容并将其存储到数组中。 但是,它不会打印文件中的所有名称,而是仅打印最后一行 Matthew 789 30 次。我的打印功能看起来正确,但不确定我哪里出错了。
主要
while (fscanf( in , "%s %s", name, num) == 2) {
array_of_students[i] = make_node(name, num);
}
printf("\nOriginal unsorted array\n");
print_array(array_of_students, 30);
功能:
Student * make_node(char * name, char * number) {
Student * new_student;
new_student = (Student * ) malloc(CLASS_SIZE * sizeof(Student));
int i = 0;
new_student[i].name = NULL;
new_student[i].number = NULL;
new_student[i].name = name;
new_student[i].number = number;
i++;
return new_student;
}
void print_array(Student * array_of_students[], int size) {
for (int i = 0; i < 30; i++) {
printf("%s %s\n", array_of_students[i] -> name, array_of_students[i] -> number);
}
}
txt 文件:
John 123
Walter 456
Matthew 789
【问题讨论】: