C语言书管理系统,结构体book中有书名和作者,构建结构体数组,实现数组初始化、 添加、删除、查询(按书名、按作者)、 输出(全部、查询结果)
时间: 2023-06-20 09:07:55 浏览: 265
下面是一个简单的C语言书籍管理系统,包括结构体的定义、结构体数组的初始化、添加、删除、查询(按书名、按作者)、输出(全部、查询结果)操作:
```c
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
// 书籍结构体
struct book {
char title[50]; // 书名
char author[30]; // 作者
};
struct book books[MAX_BOOKS]; // 书籍结构体数组
int num_books = 0; // 当前书籍数量
// 初始化书籍数组
void init_books() {
num_books = 3;
strcpy(books[0].title, "C Programming Language");
strcpy(books[0].author, "K&R");
strcpy(books[1].title, "The Art of Computer Programming");
strcpy(books[1].author, "Donald Knuth");
strcpy(books[2].title, "Structure and Interpretation of Computer Programs");
strcpy(books[2].author, "Harold Abelson and Gerald Jay Sussman");
}
// 添加新书籍
void add_book() {
if (num_books >= MAX_BOOKS) {
printf("Error: too many books!\n");
return;
}
printf("Enter book title: ");
scanf("%s", books[num_books].title);
printf("Enter book author: ");
scanf("%s", books[num_books].author);
num_books++;
}
// 删除书籍
void del_book() {
char title[50];
printf("Enter book title to delete: ");
scanf("%s", title);
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].title, title) == 0) {
// 找到匹配的书籍,将后面的书籍向前移动
for (int j = i; j < num_books - 1; j++) {
books[j] = books[j + 1];
}
num_books--;
printf("Book deleted successfully.\n");
return;
}
}
printf("Error: book not found!\n");
}
// 按书名查询书籍
void search_by_title() {
char title[50];
printf("Enter book title to search: ");
scanf("%s", title);
printf("Search results:\n");
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].title, title) == 0) {
printf("%s by %s\n", books[i].title, books[i].author);
}
}
}
// 按作者查询书籍
void search_by_author() {
char author[30];
printf("Enter book author to search: ");
scanf("%s", author);
printf("Search results:\n");
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].author, author) == 0) {
printf("%s by %s\n", books[i].title, books[i].author);
}
}
}
// 输出全部书籍
void print_all_books() {
printf("There are %d books in the library:\n", num_books);
for (int i = 0; i < num_books; i++) {
printf("%s by %s\n", books[i].title, books[i].author);
}
}
int main() {
init_books();
int choice;
while (1) {
printf("\n1. Add a book\n");
printf("2. Delete a book\n");
printf("3. Search by title\n");
printf("4. Search by author\n");
printf("5. Print all books\n");
printf("6. Exit\n");
printf("Enter your choice (1-6): ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
del_book();
break;
case 3:
search_by_title();
break;
case 4:
search_by_author();
break;
case 5:
print_all_books();
break;
case 6:
return 0;
default:
printf("Invalid choice!\n");
}
}
return 0;
}
```
注意,这只是一个简单的示例,实际应用中可能还需要加入更多的功能和错误处理。
阅读全文