学生管理系统C语言代码用到文件学生表课程表成绩表
时间: 2023-08-18 18:00:13 浏览: 198
以下是一个使用文件存储学生表、课程表和成绩表的学生管理系统的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
#define MAX_NAME_LENGTH 50
#define MAX_COURSES 10
struct Student {
char name[MAX_NAME_LENGTH];
int age;
int courseCount;
char courses[MAX_COURSES][MAX_NAME_LENGTH];
float scores[MAX_COURSES];
};
struct Student students[MAX_STUDENTS];
int studentCount = 0;
void addStudent() {
if (studentCount >= MAX_STUDENTS) {
printf("学生数量已达上限!\n");
return;
}
struct Student newStudent;
printf("请输入学生姓名:");
scanf("%s", newStudent.name);
printf("请输入学生年龄:");
scanf("%d", &newStudent.age);
printf("请输入学生选修课程数量:");
scanf("%d", &newStudent.courseCount);
for (int i = 0; i < newStudent.courseCount; i++) {
printf("请输入第%d门课程名称:", i+1);
scanf("%s", newStudent.courses[i]);
printf("请输入第%d门课程成绩:", i+1);
scanf("%f", &newStudent.scores[i]);
}
students[studentCount] = newStudent;
studentCount++;
printf("添加成功!\n");
}
void printStudents() {
if (studentCount == 0) {
printf("没有学生记录!\n");
return;
}
for (int i = 0; i < studentCount; i++) {
printf("姓名:%s\t年龄:%d\n", students[i].name, students[i].age);
printf("选修课程和成绩:\n");
for (int j = 0; j < students[i].courseCount; j++) {
printf("%s\t%.2f\n", students[i].courses[j], students[i].scores[j]);
}
}
}
void saveData() {
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("无法打开文件!\n");
return;
}
fprintf(fp, "%d\n", studentCount);
for (int i = 0; i < studentCount; i++) {
fprintf(fp, "%s %d %d\n", students[i].name, students[i].age, students[i].courseCount);
for (int j = 0; j < students[i].courseCount; j++) {
fprintf(fp, "%s %f\n", students[i].courses[j], students[i].scores[j]);
}
}
fclose(fp);
printf("数据保存成功!\n");
}
void loadData() {
FILE *fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("无法打开文件!\n");
return;
}
fscanf(fp, "%d", &studentCount);
for (int i = 0; i < studentCount; i++) {
fscanf(fp, "%s %d %d", students[i].name, &students[i].age, &students[i].courseCount);
for (int j = 0; j < students[i].courseCount; j++) {
fscanf(fp, "%s %f", students[i].courses[j], &students[i].scores[j]);
}
}
fclose(fp);
printf("数据加载成功!\n");
}
int main() {
int choice;
loadData(); // 加载数据
while (1) {
printf("\n学生管理系统\n");
printf("1. 添加学生\n");
printf("2. 查看学生\n");
printf("3. 保存数据\n");
printf("4. 退出\n");
printf("请选择操作:");
scanf("%d", &choice);
switch (choice) {
case 1:
addStudent();
break;
case 2:
printStudents();
break;
case 3:
saveData();
break;
case 4:
printf("退出程序。\n");
exit(0);
default:
printf("无效的选择!\n");
}
}
return 0;
}
```
在这个示例中,学生的信息(包括姓名、年龄、选修课程和成绩)被存储在一个结构体数组中,并使用文件进行持久化存储。通过 `saveData()` 函数将数据保存到名为 "students.txt" 的文件中,通过 `loadData()` 函数从文件中加载数据。当程序启动时,会自动加载之前保存的数据。可以根据需要修改文件名和文件格式。
阅读全文