练习三 结构体练习

用结构体数组,完成宠物信息登记管理,管理宠物的名字,品种,年龄。实现功能为插入宠物信息,遍历宠物信息,根据名字修改宠物年龄

#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;
}
 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值