使用c++单链表实现校园卡信息的管理,属性包括:卡号(字符型),姓名(字符型),余额(整型),密码(六位字符型)
时间: 2023-12-19 18:06:23 浏览: 200
以下是一个简单的实现,包括添加、删除、修改、查找和展示功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 20
#define PASSWORD_LENGTH 6
typedef struct student_card {
char id[20]; // 卡号
char name[MAX_NAME_LENGTH]; // 姓名
int balance; // 余额
char password[PASSWORD_LENGTH + 1]; // 密码
struct student_card *next; // 下一个节点
} StudentCard;
// 添加校园卡信息
void add_student_card(StudentCard **head) {
StudentCard *new_card = (StudentCard *)malloc(sizeof(StudentCard));
printf("请输入卡号:");
scanf("%s", new_card->id);
printf("请输入姓名:");
scanf("%s", new_card->name);
printf("请输入余额:");
scanf("%d", &new_card->balance);
printf("请输入密码:");
scanf("%s", new_card->password);
new_card->next = NULL;
// 将新节点插入链表头部
if (*head == NULL) {
*head = new_card;
} else {
new_card->next = *head;
*head = new_card;
}
}
// 删除校园卡信息
void delete_student_card(StudentCard **head, char *id) {
StudentCard *current = *head;
StudentCard *prev = NULL;
while (current != NULL) {
if (strcmp(current->id, id) == 0) {
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
printf("删除成功!\n");
return;
}
prev = current;
current = current->next;
}
printf("找不到该卡号对应的信息!\n");
}
// 修改校园卡信息
void modify_student_card(StudentCard *head, char *id) {
StudentCard *current = head;
while (current != NULL) {
if (strcmp(current->id, id) == 0) {
printf("请输入新的姓名:");
scanf("%s", current->name);
printf("请输入新的余额:");
scanf("%d", ¤t->balance);
printf("请输入新的密码:");
scanf("%s", current->password);
printf("修改成功!\n");
return;
}
current = current->next;
}
printf("找不到该卡号对应的信息!\n");
}
// 查找校园卡信息
void search_student_card(StudentCard *head, char *id) {
StudentCard *current = head;
while (current != NULL) {
if (strcmp(current->id, id) == 0) {
printf("卡号:%s,姓名:%s,余额:%d,密码:%s\n", current->id, current->name, current->balance, current->password);
return;
}
current = current->next;
}
printf("找不到该卡号对应的信息!\n");
}
// 展示所有校园卡信息
void show_student_cards(StudentCard *head) {
StudentCard *current = head;
printf("卡号\t\t姓名\t\t余额\t\t密码\n");
while (current != NULL) {
printf("%s\t\t%s\t\t%d\t\t%s\n", current->id, current->name, current->balance, current->password);
current = current->next;
}
}
int main() {
StudentCard *head = NULL;
int choice;
char id[20];
while (1) {
printf("\n1.添加学生卡信息\n2.删除学生卡信息\n3.修改学生卡信息\n4.查找学生卡信息\n5.展示学生卡信息\n6.退出\n");
printf("请选择操作:");
scanf("%d", &choice);
switch (choice) {
case 1:
add_student_card(&head);
break;
case 2:
printf("请输入要删除的卡号:");
scanf("%s", id);
delete_student_card(&head, id);
break;
case 3:
printf("请输入要修改的卡号:");
scanf("%s", id);
modify_student_card(head, id);
break;
case 4:
printf("请输入要查找的卡号:");
scanf("%s", id);
search_student_card(head, id);
break;
case 5:
show_student_cards(head);
break;
case 6:
printf("再见!\n");
exit(0);
default:
printf("请输入正确的选项!\n");
break;
}
}
return 0;
}
```
阅读全文