【发布时间】:2021-11-20 23:15:23
【问题描述】:
我有两个必须用学生数据填充的结构。数据格式为:
年龄、姓名、年级、年龄、组别、轮次
文件头中是数据中的学生人数。
struct school //school
{
char group; //A,B,C,D,E,F
char turn; //Morning, AFTERNOON
};
struct student
{
char *name;
char *grade;
int age;
struct school *E;
}student[6];
我尝试先从只有年龄、姓名和年级的文本中保存数据,看看我是否可以做到:
void get_file(const char* file, int *n){ //n is the amount of students
FILE* fptr;
fptr = fopen(file, "r");
if (fptr == NULL){
printf( "\n Error \n");
exit(1);
}
char* temp;
int tam = 0;
fscanf(fptr, "%d", n); //size of the list of students
for(int i= 0; i < *n; i++){
fscanf(fptr, "%d,%s,%s", &student.age[i],temp, student[i].grade);
tam = strlen(temp);
student[i].name = (char*)malloc(tam * sizeof(char));
strcpy(student[i].name, temp);
printf("%s\n", student[i].name);//to see if it's correct the content
}
fclose(fptr);
}
但是,student.name 存储例如 "Josh, A+",而它应该只是 "Josh"。我该如何解决这个问题?
这是一个任务。
编辑: 我的数据是这样的
4 //size of list
Josh,A,20,D,M
Amber,B,23,E,M
Kevin,C,22,D,A
Adam,A+,21,C,A
使用 Remy Lebeau 的解决方案,我得到了这个
void get_file(const char* file, int *n){
*n = 0;
FILE* fptr = fopen(file, "r");
if (fptr == NULL){
printf( "\n Error \n");
exit(1);
}
char name[80];
char grade[2];
fscanf(fptr, "%d", n); //size of the list of students
for(int i = 0; i < *n; i++){
fscanf(fptr, "%80[^,],%2[^,],%d,%c,%c", &student[i].age, name, grade,&student[i].group, &student[i].turn);
student[i].name = strdup(name);
student[i].grade = strdup(grade);
}
fclose(fptr);
}
但是我遇到了问题,因为我做了这个改变
struct student
{
char *name;
char *grade;
int age;
struct school E; //it was struct school *E
}student[6];
要传递信息,但是老师说我不能改,那我怎么加载struct school *E的信息呢?
【问题讨论】:
-
发布答案后,请不要通过应用答案中建议的更正来更改您的问题,因为这会使答案无效。
-
将数据从文件移动到内存中通常称为加载,而不是保存。
标签: c string pointers data-structures struct