struct框架实现增删改查
时间: 2023-07-07 17:29:58 浏览: 122
用struts1实现的增删改查功能
5星 · 资源好评率100%
好的,这是一个常见的问题,我可以为您提供一个简单的 struct 实现增删改查的框架,具体实现可能需要根据具体需求进行修改:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
/* 定义结构体 */
struct student {
char name[MAX_LEN];
int age;
float score;
};
/* 定义全局变量 */
int count = 0; // 学生数量
struct student students[MAX_LEN];
/* 函数声明 */
void add_student(void);
void delete_student(void);
void modify_student(void);
void search_student(void);
void print_student(void);
int main(void) {
int choice;
/* 循环菜单 */
while (1) {
printf("\nMenu:\n");
printf("1. Add student\n");
printf("2. Delete student\n");
printf("3. Modify student\n");
printf("4. Search student\n");
printf("5. Print all students\n");
printf("6. Exit\n");
printf("Please enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_student();
break;
case 2:
delete_student();
break;
case 3:
modify_student();
break;
case 4:
search_student();
break;
case 5:
print_student();
break;
case 6:
return 0;
default:
printf("Invalid choice!\n");
break;
}
}
}
/* 添加学生 */
void add_student(void) {
if (count >= MAX_LEN) {
printf("The number of students has reached the maximum!\n");
return;
}
struct student s;
printf("Please enter student name: ");
scanf("%s", s.name);
printf("Please enter student age: ");
scanf("%d", &s.age);
printf("Please enter student score: ");
scanf("%f", &s.score);
students[count++] = s;
printf("Student added successfully!\n");
}
/* 删除学生 */
void delete_student(void) {
char name[MAX_LEN];
printf("Please enter student name to delete: ");
scanf("%s", name);
for (int i = 0; i < count; i++) {
if (strcmp(students[i].name, name) == 0) {
/* 将最后一个学生覆盖当前学生,然后数量减一 */
students[i] = students[--count];
printf("Student deleted successfully!\n");
return;
}
}
printf("Student not found!\n");
}
/* 修改学生信息 */
void modify_student(void) {
char name[MAX_LEN];
printf("Please enter student name to modify: ");
scanf("%s", name);
for (int i = 0; i < count; i++) {
if (strcmp(students[i].name, name) == 0) {
printf("Please enter new age: ");
scanf("%d", &students[i].age);
printf("Please enter new score: ");
scanf("%f", &students[i].score);
printf("Student modified successfully!\n");
return;
}
}
printf("Student not found!\n");
}
/* 查找学生信息 */
void search_student(void) {
char name[MAX_LEN];
printf("Please enter student name to search: ");
scanf("%s", name);
for (int i = 0; i < count; i++) {
if (strcmp(students[i].name, name) == 0) {
printf("Name: %s, Age: %d, Score: %.2f\n", students[i].name, students[i].age, students[i].score);
return;
}
}
printf("Student not found!\n");
}
/* 打印所有学生信息 */
void print_student(void) {
if (count == 0) {
printf("No students!\n");
return;
}
printf("All students:\n");
for (int i = 0; i < count; i++) {
printf("Name: %s, Age: %d, Score: %.2f\n", students[i].name, students[i].age, students[i].score);
}
}
```
这个代码框架实现了一个简单的学生管理系统,可以实现添加、删除、修改、查找和打印学生信息的功能。您可以根据实际需要进行修改和扩展。
阅读全文