1用结构体数组,完成宠物信息登记管理,管理宠物的名字,品种,年龄。实现功能为插入宠物信息,遍历宠物信息.
#include <stdio.h>
#define MAX_PETS 100
// 宠物结构体
struct Pet {
char name[50];
char breed[50];
int age;
};
// 插入宠物信息
void insertPetInfo(struct Pet pets[], int *numPets) {
if (*numPets < MAX_PETS) {
struct Pet newPet;
printf("Enter pet name: ");
scanf("%s", newPet.name);
printf("Enter pet breed: ");
scanf("%s", newPet.breed);
printf("Enter pet age: ");
scanf("%d", &newPet.age);
pets[*numPets] = newPet;
(*numPets)++;
printf("Pet information inserted successfully.\n");
} else {
printf("Cannot insert more pets. Maximum limit reached.\n");
}
}
// 遍历宠物信息
void displayPetInfo(struct Pet pets[], int numPets) {
printf("Pet Information:\n");
for (int i = 0; i < numPets; i++) {
printf("Pet %d:\n", i + 1);
printf("Name: %s\n", pets[i].name);
printf("Breed: %s\n", pets[i].breed);
printf("Age: %d\n", pets[i].age);
printf("\n");
}
}
int main() {
struct Pet pets[MAX_PETS];
int numPets = 0;
int choice;
do {
printf("1. Insert pet information\n");
printf("2. Display pet information\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insertPetInfo(pets, &numPets);
break;
case 2:
displayPetInfo(pets, numPets);
break;
case 3:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 3);
return 0;
}