帮忙看看题:
给定结构体数据类型 typedef struct stu { long stuID,
char stuName[10],
float scoreEMP[3],
}STU;
编写程序完成如下功能:主函数定义基于结构体STU数据类型的5名学生的数组student,调用函数void inputData(STU *ptr)通过键盘输入5名学生的信息,调用函数void writeToFile(STU *ptr)把5名学生的信息按文本格式写入到文件“student.txt"中。
完整的代码实现如下,望采纳
#include <stdio.h>
#include <stdlib.h>
// 定义结构体数据类型
typedef struct stu {
long stuID;
char stuName[10];
float scoreEMP[3];
} STU;
// 定义输入函数
void inputData(STU *ptr)
{
// 遍历学生数组
for (int i = 0; i < 5; i++) {
printf("请输入第 %d 名学生的信息:\n", i + 1);
printf("学号:");
scanf("%ld", &(ptr[i].stuID));
printf("姓名:");
scanf("%s", ptr[i].stuName);
printf("三门课的成绩:");
scanf("%f %f %f", &(ptr[i].scoreEMP[0]), &(ptr[i].scoreEMP[1]), &(ptr[i].scoreEMP[2]));
}
}
// 定义写入函数
void writeToFile(STU *ptr)
{
// 打开文件
FILE *fp = fopen("student.txt", "w");
if (fp == NULL) {
printf("无法打开文件!\n");
exit(1);
}
// 遍历学生数组,并按文本格式写入到文件
for (int i = 0; i < 5; i++) {
fprintf(fp, "学号:%ld\n", ptr[i].stuID);
fprintf(fp, "姓名:%s\n", ptr[i].stuName);
fprintf(fp, "三门课的成绩:%.2f %.2f %.2f\n", ptr[i].scoreEMP[0], ptr[i].scoreEMP[1], ptr[i].scoreEMP[2]);
}
// 关闭文件
fclose(fp);
}
int main()
{
// 定义基于结构体 STU 数据类型的 5 名学生的数组
STU student[5];
// 调用输入函数
inputData(student);
// 调用写入函数
writeToFile(student);
return 0;
}