用C语言写一个图书管理系统
时间: 2023-10-03 21:11:15 浏览: 25
好的,下面是一个简单的图书管理系统的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
struct book {
int book_id;
char title[50];
char author[50];
int year_published;
};
struct book books[MAX_BOOKS];
int num_books = 0;
void add_book()
{
if (num_books >= MAX_BOOKS) {
printf("Error: Maximum number of books reached.\n");
return;
}
struct book new_book;
printf("Enter book ID: ");
scanf("%d", &new_book.book_id);
printf("Enter book title: ");
scanf("%s", new_book.title);
printf("Enter book author: ");
scanf("%s", new_book.author);
printf("Enter year published: ");
scanf("%d", &new_book.year_published);
books[num_books] = new_book;
num_books++;
printf("Book added successfully.\n");
}
void list_books()
{
if (num_books == 0) {
printf("No books in the library.\n");
return;
}
printf("Book ID\tTitle\tAuthor\tYear Published\n");
for (int i = 0; i < num_books; i++) {
printf("%d\t%s\t%s\t%d\n", books[i].book_id, books[i].title, books[i].author, books[i].year_published);
}
}
void search_book()
{
int book_id;
printf("Enter book ID to search: ");
scanf("%d", &book_id);
for (int i = 0; i < num_books; i++) {
if (books[i].book_id == book_id) {
printf("Book ID\tTitle\tAuthor\tYear Published\n");
printf("%d\t%s\t%s\t%d\n", books[i].book_id, books[i].title, books[i].author, books[i].year_published);
return;
}
}
printf("Book not found.\n");
}
void delete_book()
{
int book_id;
printf("Enter book ID to delete: ");
scanf("%d", &book_id);
for (int i = 0; i < num_books; i++) {
if (books[i].book_id == book_id) {
for (int j = i; j < num_books - 1; j++) {
books[j] = books[j + 1];
}
num_books--;
printf("Book deleted successfully.\n");
return;
}
}
printf("Book not found.\n");
}
int main()
{
int choice;
while (1) {
printf("\n");
printf("1. Add book\n");
printf("2. List books\n");
printf("3. Search book\n");
printf("4. Delete book\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
list_books();
break;
case 3:
search_book();
break;
case 4:
delete_book();
break;
case 5:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
```
这个示例程序实现了以下功能:
- 添加书籍
- 列出书籍
- 搜索书籍
- 删除书籍
它使用一个结构体 `book` 来存储每本书的信息,然后将这些结构体存储在一个数组中。用户可以选择要执行的操作,然后程序将调用相应的函数来处理请求。