C语言实现十分简单的学生管理系统
描述
该程序使用结构体定义学生的信息,可以添加、删除和打印学生信息。使用了一个无限循环来接收用户的输入并执行相应的操作。在每个操作之后,程序会重新回到循环中等待下一次输入。
十分简单的一种实现方式,可以应付下实验报告…,可以自行将一些功能封装成函数,增强可读性。
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
typedef struct {
char name[MAX_NAME_LEN];
int id;
float score;
} student_t;
int main() {
student_t students[100];
int num_students = 0;
while (1) {
printf("\n1. Add student\n");
printf("2. Remove student\n");
printf("3. Print all students\n");
printf("4. Quit\n\n");
printf("Enter your choice (1-4): ");
int choice;
scanf("%d", &choice);
switch (choice) {
case 1: {
if (num_students >= 100) {
printf("Error: maximum number of students reached.\n");
break;
}
student_t new_student;
printf("Enter student name: ");
scanf("%s", new_student.name);
printf("Enter student ID: ");
scanf("%d", &new_student.id);
printf("Enter student score: ");
scanf("%f", &new_student.score);
students[num_students] = new_student;
num_students++;
printf("Student added successfully.\n");
break;
}
case 2: {
if (num_students == 0) {
printf("Error: there are no students to remove.\n");
break;
}
printf("Enter student ID to remove: ");
int id;
scanf("%d", &id);
int index_to_remove = -1;
for (int i = 0; i < num_students; i++) {
if (students[i].id == id) {
index_to_remove = i;
break;
}
}
if (index_to_remove == -1) {
printf("Error: student with ID %d not found.\n", id);
break;
}
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("There are no students to display.\n");
break;
}
printf("Name\tID\tScore\n");
for (int i = 0; i < num_students; i++) {
printf("%s\t%d\t%.2f\n", students[i].name, students[i].id, students[i].score);
}
break;
}
case 4: {
printf("Exiting program.\n");
exit(0);
}
default: {
printf("Error: invalid choice. Please enter a number between 1 and 4.\n");
break;
}
}
}
return 0;
}