7. 添加学生功能的实现
我将对学生的操作放在了 class_room 这个模块中。其中包括添加学生、删除学生,修改成绩等功能。在此模块的系列函数中都传入一个指针 class_room_t *aclass, 这个指针 aclass 指向要操作班级的结构体。
在添加学生前需要判断当前班级的学生数(student_count)是否达到了班级最大容纳的学生数(MAX_STU_COUNT_IN_CLASS_ROOM),如果达到最大容量则放弃添加。
添加学生是先要输入姓名、语文成绩、数学成绩,验证是否符合逻辑要求,如果不符合要求则退出添加。否则将如下信息填入班级的学生数组 aclass->student 的末尾,然后将班级学生数 aclass->student_count 做加一操作。
具体代码如下
文件 class_room.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "tools.h"
#include "student.h"
#include "class_room.h"
// 添加学生信息
void add_student(class_room_t *aclass)
{
char student_name[MAX_STU_NAME_LEN*2];
int chinese_score;
int math_score;
if (aclass->student_count >= MAX_STU_COUNT_IN_CLASS_ROOM) {
printf("班级 %s 学生已满,如法添加学生信息\n", aclass->class_title);
return;
}
printf("请输入学生姓名: ");
fflush(stdout);
scanf("%s", student_name);
// fgets(student_name, sizeof(student_name), stdin);
if (strlen(student_name) >= MAX_STU_NAME_LEN) {
printf("学生的名字太长,添加失败!\n");
return;
}
printf("请输入学生的语文成绩: ");
fflush(stdout);
scanf("%d", &chinese_score);
if (chinese_score < 0 || chinese_score > 100) {
printf("学生成绩不在合法范围内,添加失败!\n");
return;
}
printf("请输入学生的数学成绩: ");
fflush(stdout);
scanf("%d", &math_score);
if (math_score < 0 || math_score > 100) {
printf("学生成绩不在合法范围内,添加失败!\n");
return;
}
student_t astu;
strcpy(astu.name, student_name);
astu.chinese_score = chinese_score;
astu.math_score = math_score;
aclass->student[aclass->student_count] = astu;
aclass->student_count++;
printf("添加学生 %s 成功!", student_name);
}