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