怎么用fscanf把学号:5| 姓名:1| 性别:1| 地址:1| 电话:1| 语文:0| 数学:0| 外语:0| 考试成绩:0.000| 名次:0| 品德:0| 综合分:0| 综合名次:0| 导入单向链表中
时间: 2023-08-12 08:42:36 浏览: 116
创建包含学号、姓名节点的单链表
假设你的输入文件格式为:
5|1|1|1|1|0|0|0|0.000|0|0|0|0|
可以使用以下代码读取文件并将其导入单向链表中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 100
struct student {
int id;
char name[MAX_LENGTH];
char gender[MAX_LENGTH];
char address[MAX_LENGTH];
char phone[MAX_LENGTH];
int chinese;
int math;
int english;
float score;
int rank;
int morality;
int comprehensive_score;
int comprehensive_rank;
struct student *next;
};
int main() {
FILE *fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Failed to open file\n");
exit(1);
}
struct student *head = NULL;
struct student *tail = NULL;
char line[MAX_LENGTH];
while (fgets(line, MAX_LENGTH, fp) != NULL) {
struct student *s = (struct student*) malloc(sizeof(struct student));
sscanf(line, "%d|%[^|]|%[^|]|%[^|]|%[^|]|%d|%d|%d|%f|%d|%d|%d|%d|",
&s->id, s->name, s->gender, s->address, s->phone,
&s->chinese, &s->math, &s->english, &s->score,
&s->rank, &s->morality, &s->comprehensive_score, &s->comprehensive_rank);
s->next = NULL;
if (head == NULL) {
head = s;
tail = s;
} else {
tail->next = s;
tail = s;
}
}
// Do something with the linked list here
fclose(fp);
return 0;
}
```
在上面的代码中,我们首先打开文件并检查是否成功打开。然后,我们定义了一个 `struct student` 结构体来表示每个学生的信息。我们使用 `fgets` 函数逐行读取文件,使用 `sscanf` 函数将每行数据解析为 `struct student` 结构体。最后,我们将每个 `struct student` 结构体插入到单向链表中。你可以在上面的代码中添加你自己的逻辑来处理单向链表。
阅读全文