请用c语言帮我写一个模块化的图书管理系统
时间: 2023-06-04 08:03:20 浏览: 92
好的,我可以帮你写一个模块化的图书管理系统。以下是示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义图书结构体
typedef struct Book {
char title[50];
char author[50];
int pages;
int year;
} Book;
// 定义图书馆结构体
typedef struct Library {
Book* books[100];
int count;
} Library;
// 函数声明
void addBook(Library* library);
void searchBook(Library* library);
void deleteBook(Library* library);
void displayMenu();
int main() {
Library library;
library.count = 0;
int choice;
do {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
addBook(&library);
break;
case 2:
searchBook(&library);
break;
case 3:
deleteBook(&library);
break;
case 4:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice. Please try again.\n");
break;
}
} while (choice != 4);
return 0;
}
void addBook(Library* library) {
if (library->count == 100) {
printf("Library is already full.\n");
return;
}
Book* newBook = (Book*) malloc(sizeof(Book));
printf("Enter book title: ");
scanf("%s", newBook->title);
printf("Enter book author: ");
scanf("%s", newBook->author);
printf("Enter number of pages: ");
scanf("%d", &newBook->pages);
printf("Enter year published: ");
scanf("%d", &newBook->year);
library->books[library->count] = newBook;
library->count++;
printf("Book added successfully!\n");
}
void searchBook(Library* library) {
char searchTerm[50];
printf("Enter search term: ");
scanf("%s", searchTerm);
for (int i = 0; i < library->count; i++) {
Book* book = library->books[i];
if (strstr(book->title, searchTerm) != NULL || strstr(book->author, searchTerm) != NULL) {
printf("%s by %s (%d pages, %d)\n", book->title, book->author, book->pages, book->year);
}
}
}
void deleteBook(Library* library) {
char deleteTitle[50];
printf("Enter title of book to delete: ");
scanf("%s", deleteTitle);
int deleted = 0;
for (int i = 0; i < library->count; i++) {
Book* book = library->books[i];
if (strcmp(book->title, deleteTitle) == 0) {
free(book);
library->books[i] = NULL;
deleted = 1;
break;
}
}
if (deleted) {
for (int i = 0; i < library->count; i++) {
if (library->books[i] == NULL) {
if (i != library->count - 1) {
library->books[i] = library->books[i + 1];
}
library->count--;
}
}
printf("Book deleted successfully!\n");
} else {
printf("Book not found.\n");
}
}
void displayMenu() {
printf("\n");
printf("----------\n");
printf("MENU\n");
printf("----------\n");
printf("1. Add book\n");
printf("2. Search for book\n");
printf("3. Delete book\n");
printf("4. Exit\n");
printf("Enter your choice: ");
}
```
这个图书管理系统包含了添加图书、搜索图书、删除图书的功能,并且使用了模块化的编程方法,将图书和图书馆分别封装成了结构体。你可以根据需要进行修改和扩展。
阅读全文