gpt4 book ai didi

c - 读取数据文件并存储到结构数组中

转载 作者:行者123 更新时间:2023-11-30 19:52:20 26 4
gpt4 key购买 nike

我正在尝试读取数据文件并将信息存储到类(class)结构数组(或指向类(class)结构的指针数组)中。该作业需要使用指向学生结构的指针数组来维护数据库。

当我尝试将数据文件扫描到数组中时,出现段错误。如何正确地将文件中的信息存储到数组中?

#define SIZE        30
#define fieldLength 300
#define diskFile "diskFile.dat"
#define courseFile "course.dat"

struct student
{
char name[fieldLength];
int age[fieldLength];
char course1[fieldLength];
char course2[fieldLength];
char remarks[fieldLength];
}*sp[SIZE];

struct course
{
char name[fieldLength];
char number[fieldLength];
char instructor[fieldLength];
char date[fieldLength];
char starting[fieldLength];
char ending[fieldLength];
char location[fieldLength];
};

int main(int argc, char *argv[])
{
int i, count;

struct course course_arr[SIZE]; // an array of ten structs

FILE * in; /*FILE pointer to do the stream IO*/
in = fopen(courseFile, "r+");

count = 0;
while ((fscanf(in, "%s %s %s %s %s %s %s",
&course_arr[count].name,
&course_arr[count].number,
&course_arr[count].instructor,
&course_arr[count].date,
&course_arr[count].starting,
&course_arr[count].ending,
&course_arr[count].location)) != EOF)
{
count++;
}

/* print the menu */
printf("\n-----------------------------------------------------------------\n");
printf("|\t%-20s","(N)ew record");
printf("%-20s","(U)pdate record");
printf("Swa(p) records\t|\n");
printf("|\t%-20s","(S)ort database");
printf("%-20s","(C)lear database");
printf("(D)isplay db\t|\n");

printf("|\t%-20s","(L)oad disk");
printf("%-20s","(W)rite disk");
printf("(E)mpty disk\t|\n");

printf("|\t%-20s", "(V)iew courses");
printf("%-20s","(R)emove record");
printf("(Q)uit \t|\n");
printf("-----------------------------------------------------------------\n");
printf("choose one: ");

最佳答案

例程fscanf永远不会返回EOF。测试 fscanf 是否小于预期字段数:

count = 0;
while((fscanf(in, "%s %s %s %s %s %s %s", &course_arr[count].name, &course_arr[count].number, &course_arr[count].instructor, &course_arr[count].date, &course_arr[count].starting, &course_arr[count].ending, &course_arr[count].location)) < 7){
count++;
}

关于c - 读取数据文件并存储到结构数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17633966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com