使用C语言编写一个简单的宠物信息管理系统代码,可以实现宠物信息录入和删除
时间: 2023-03-23 09:00:13 浏览: 228
好的,下面是一个简单的宠物信息管理系统代码,使用C语言编写,可以实现宠物信息录入和删除的功能:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PETS 100
typedef struct {
char name[20];
int age;
char breed[20];
} Pet;
Pet pets[MAX_PETS];
int num_pets = 0;
void add_pet() {
if (num_pets == MAX_PETS) {
printf("Sorry, the database is full and cannot add more pets.\n");
return;
}
Pet new_pet;
printf("Enter the name of the pet: ");
scanf("%s", new_pet.name);
printf("Enter the age of the pet: ");
scanf("%d", &new_pet.age);
printf("Enter the breed of the pet: ");
scanf("%s", new_pet.breed);
pets[num_pets] = new_pet;
num_pets++;
printf("The pet has been added to the database.\n");
}
void remove_pet() {
if (num_pets == 0) {
printf("Sorry, the database is empty and cannot remove any pets.\n");
return;
}
char name[20];
printf("Enter the name of the pet to remove: ");
scanf("%s", name);
int index = -1;
for (int i = 0; i < num_pets; i++) {
if (strcmp(pets[i].name, name) == 0) {
index = i;
break;
}
}
if (index == -1) {
printf("Sorry, the pet with name %s cannot be found in the database.\n", name);
return;
}
for (int i = index; i < num_pets - 1; i++) {
pets[i] = pets[i + 1];
}
num_pets--;
printf("The pet with name %s has been removed from the database.\n", name);
}
int main() {
int choice;
do {
printf("\n\n");
printf("1. Add a pet\n");
printf("2. Remove a pet\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_pet();
break;
case 2:
remove_pet();
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice. Please enter a valid choice.\n");
break;
}
} while (choice != 3);
return 0;
}
```
这个程序中,我们使用了一个结构体 `Pet` 来存储宠物的信息,包括名字、年龄和品种。我们使用一个数组 `pets` 来存储所有的宠物信息,其中 `num_pets` 记录了当前已经录入的宠物数量。程序提供了两个功能,分别是添加宠物和删除宠物。在添加宠物时,程序会提示用户输入宠物的名字、年龄和品种,并将新的宠物信息存储到数组 `pets` 中。在删除宠物时,程序会提示用户输入要删除的宠物的名字,并在数组 `pets` 中查找