从文本文件“ex804.txt”格式化读取学生信息,然后将学生信息封装到结构体数组中,最后在标准输出设备中输出显示。 (1)“ex804.txt”的存储组织格式为:每行只保存一个同学信息;每行(每个同学)共有4个数据,分别为学号、姓名、年龄、成绩,每个数据之间以空格分隔。注:文本文件“ex804.txt”应与源文件“ex804.c”保存在同一个文件夹中。 (2)学生结构体定义如下: struct stu{ int id; //学号 char name[20]; //姓名 int age; //年龄 int score; //成绩 }; 目前,已完成main函数的编写,请编程实现“readFileForStu”函数和“stdoutForStu”函数。
时间: 2023-11-22 19:55:47 浏览: 101
以下是“readFileForStu”函数和“stdoutForStu”函数的实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stu{
int id; //学号
char name[20]; //姓名
int age; //年龄
int score; //成绩
};
void readFileForStu(struct stu *stuArr, int len, char *filename) {
FILE* fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s", filename);
return;
}
char buf[100];
for (int i = 0; i < len; i++) {
fgets(buf, 100, fp);
sscanf(buf, "%d %s %d %d", &stuArr[i].id, stuArr[i].name, &stuArr[i].age, &stuArr[i].score);
}
fclose(fp);
}
void stdoutForStu(struct stu *stuArr, int len) {
printf("|%-10s|%-20s|%-10s|%-10s|\n", "ID", "Name", "Age", "Score");
for (int i = 0; i < len; i++) {
printf("|%-10d|%-20s|%-10d|%-10d|\n", stuArr[i].id, stuArr[i].name, stuArr[i].age, stuArr[i].score);
}
}
```
在主函数中,可以这样使用这两个函数:
```c
int main() {
int len = 5;
struct stu stuArr[len];
char *filename = "ex804.txt";
readFileForStu(stuArr, len, filename);
stdoutForStu(stuArr, len);
return 0;
}
```
其中,`len`表示学生信息数组的长度,`filename`表示存储学生信息的文件名。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)