帮我写一个学生管理系统的c语言代码
时间: 2023-08-20 12:16:06 浏览: 44
好的,以下是一个简单的学生管理系统的C语言代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100
struct student {
char name[50];
int id;
float gpa;
};
int main() {
struct student students[MAX_STUDENTS];
int num_students = 0;
int option;
do {
printf("Select an option:\n");
printf("1. Add a student\n");
printf("2. Remove a student\n");
printf("3. View all students\n");
printf("4. Exit\n");
printf("Option: ");
scanf("%d", &option);
switch(option) {
case 1:
if (num_students == MAX_STUDENTS) {
printf("Error: Maximum number of students reached\n");
} else {
struct student new_student;
printf("Enter student name: ");
scanf("%s", new_student.name);
printf("Enter student ID: ");
scanf("%d", &new_student.id);
printf("Enter student GPA: ");
scanf("%f", &new_student.gpa);
students[num_students] = new_student;
num_students++;
printf("Student added successfully\n");
}
break;
case 2:
if (num_students == 0) {
printf("Error: No students to remove\n");
} else {
int id_to_remove;
printf("Enter ID of student to remove: ");
scanf("%d", &id_to_remove);
int index_to_remove = -1;
for (int i = 0; i < num_students; i++) {
if (students[i].id == id_to_remove) {
index_to_remove = i;
break;
}
}
if (index_to_remove == -1) {
printf("Error: Student with ID %d not found\n", id_to_remove);
} else {
for (int i = index_to_remove; i < num_students - 1; i++) {
students[i] = students[i + 1];
}
num_students--;
printf("Student removed successfully\n");
}
}
break;
case 3:
if (num_students == 0) {
printf("No students in the system\n");
} else {
printf("Name\tID\tGPA\n");
for (int i = 0; i < num_students; i++) {
printf("%s\t%d\t%.2f\n", students[i].name, students[i].id, students[i].gpa);
}
}
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid option\n");
break;
}
} while(option != 4);
return 0;
}
```
这个学生管理系统可以添加、删除和查看学生信息。它使用了一个结构体来表示每个学生的信息,使用数组来存储多个学生。在添加学生时,它会检查数组是否已满,如果是,则会打印错误消息。在删除学生时,它会先要求用户输入要删除的学生的ID,然后遍历数组来查找该学生,并将其从数组中删除。在查看所有学生信息时,它会遍历数组并打印每个学生的信息。