写一个c语言程序 大学 使用顺序表实现学生名册管理程序,名册中的每条记录包括学号,姓名,联系电话等项
时间: 2024-10-22 12:27:32 浏览: 21
在C语言中,你可以创建一个简单的顺序表结构来实现大学名册管理。这里是一个基本的示例,我们将使用链表结构来存储学生的记录:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int student_id;
char name[50];
char phone_number[20];
} Student; // 定义学生结构体
// 动态分配内存并初始化一个新的学生节点
Student* create_student(int id, char* name, char* phone) {
Student* new_student = (Student*)malloc(sizeof(Student));
if (new_student != NULL) {
new_student->student_id = id;
strcpy(new_student->name, name);
strcpy(new_student->phone_number, phone);
} else {
printf("Memory allocation failed.\n");
return NULL;
}
return new_student;
}
// 在名册中添加新学生
void add_student(Student** list, Student* new_student) {
*list = (*list == NULL) ? new_student : malloc(sizeof(Student) + sizeof(Student*) * (*list)->next_size);
if (*list) {
new_student->next = &(*list)[(*list)->next_size];
(*list)->next_size++;
(*list)++;
} else {
printf("List is full or memory allocation failed.\n");
}
}
// 打印整个学生名册
void print_students(Student* list) {
if (list == NULL) {
printf("No students in the list.\n");
return;
}
while (list != NULL) {
printf("ID: %d, Name: %s, Phone: %s\n", list->student_id, list->name, list->phone_number);
list = list->next;
}
}
int main() {
Student* student_list = NULL;
int choice;
// 主循环用于操作名册
while (1) {
printf("\n1. Add student\n2. Print students\n3. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
char name[50], phone[20];
printf("Enter student ID: ");
scanf("%d", &student_list->student_id);
printf("Enter student name: ");
fgets(name, sizeof(name), stdin); // 读取直到换行符
name[strlen(name) - 1] = '\0'; // 去掉末尾的换行符
printf("Enter student phone number: ");
fgets(phone, sizeof(phone), stdin);
phone[strlen(phone) - 1] = '\0';
Student* new_student = create_student(student_list->student_id, name, phone);
if (new_student) {
add_student(&student_list, new_student);
}
break;
case 2:
print_students(student_list);
break;
case 3:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
```
这个程序实现了基本的学生名册管理功能,用户可以选择添加、打印学生信息或退出。注意,此示例仅适用于小型项目,实际应用中需要考虑内存管理和错误处理。
阅读全文