c | 结构体题

#include <stdio.h>
#include <string.h>

// 定义结构体
struct reader {
    char name[100];      // 读者姓名
    int age;             // 年龄
    char department[100];// 所在院系名称
};

struct borrow_record {
    char borrow_date[100];   // 借阅日期
    struct reader borrower;  // 借阅人
};

struct book {
    char name[100];            // 书名
    int price;                 // 价格
    struct borrow_record records[1000]; // 借阅记录,数组下标 0 ~ rec_n - 1
    int rec_n;                 // 借阅记录数
};

// 定义函数
void print_r(struct book books[], int n, char book_name[]) {
    int found = 0; // 标志变量,判断是否找到书名为 book_name 的图书

    // 遍历图书数组
    for (int i = 0; i < n; i++) {
        // 判断当前图书的书名是否与 book_name 相同
        if (strcmp(books[i].name, book_name) == 0) {
            found = 1; // 标记为找到
            printf("records for book_name: %s\n", book_name);

            // 遍历该图书的所有借阅记录
            for (int j = 0; j < books[i].rec_n; j++) {
                printf("data: %s, name: %s, age: %d, faculty: %s\n",
                       books[i].records[j].borrow_date,          // 借阅日期
                       books[i].records[j].borrower.name,        // 读者姓名
                       books[i].records[j].borrower.age,         // 读者年龄
                       books[i].records[j].borrower.department); // 所在院系
            }
            break; // 找到后退出循环
        }
    }

    // 如果未找到书名为 book_name 的图书
    if (!found) {
        printf(" no %s\n", book_name);
    }
}

int main() {
    // 创建一个图书数组
    struct book books[2] = {
            {
                    "C Programming",
                    50,
                    {
                            {"2023-01-01", {"Alice", 20, "Computer Science"}},
                            {"2023-02-01", {"Bob", 22, "Mathematics"}}
                    },
                    2
            },
            {
                    "Data Structures",
                    60,
                    {
                            {"2023-03-01", {"Charlie", 21, "Engineering"}}
                    },
                    1
            }
    };

    // 测试1:查找 "C Programming" 的借阅记录
    print_r(books, 2, "C Programming");
    printf("\n");

    // 测试2:查找 "Algorithms" 的借阅记录(不存在)
    print_r(books, 2, "Algorithms");
    printf("\n");

    // 测试3:查找 "Data Structures" 的借阅记录
    print_r(books, 2, "Data Structures");
    printf("\n");

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值