用c语言代码实现图书管理系统的创建
时间: 2023-09-16 18:14:27 浏览: 49
好的,这里是一个用C语言代码实现图书管理系统的简单例子,包括图书信息的录入、查询和打印功能。由于篇幅和复杂性的限制,这个例子仅涉及基本功能,具体实现方式也仅供参考。
```c
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
typedef struct {
char title[50];
char author[50];
char publisher[50];
int year;
int stock;
} Book;
Book books[MAX_BOOKS];
int num_books = 0;
void add_book(void) {
if (num_books >= MAX_BOOKS) {
printf("No more space for new books.\n");
return;
}
Book new_book;
printf("Enter book title: ");
fgets(new_book.title, sizeof(new_book.title), stdin);
new_book.title[strcspn(new_book.title, "\n")] = '\0';
printf("Enter book author: ");
fgets(new_book.author, sizeof(new_book.author), stdin);
new_book.author[strcspn(new_book.author, "\n")] = '\0';
printf("Enter book publisher: ");
fgets(new_book.publisher, sizeof(new_book.publisher), stdin);
new_book.publisher[strcspn(new_book.publisher, "\n")] = '\0';
printf("Enter book year: ");
scanf("%d", &new_book.year);
printf("Enter book stock: ");
scanf("%d", &new_book.stock);
getchar();
books[num_books++] = new_book;
printf("Book added successfully.\n");
}
void search_book(void) {
char title[50];
printf("Enter book title: ");
fgets(title, sizeof(title), stdin);
title[strcspn(title, "\n")] = '\0';
int found = 0;
for (int i = 0; i < num_books; i++) {
if (strcmp(title, books[i].title) == 0) {
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Publisher: %s\n", books[i].publisher);
printf("Year: %d\n", books[i].year);
printf("Stock: %d\n", books[i].stock);
found = 1;
break;
}
}
if (!found) {
printf("Book not found.\n");
}
}
void print_books(void) {
for (int i = 0; i < num_books; i++) {
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Publisher: %s\n", books[i].publisher);
printf("Year: %d\n", books[i].year);
printf("Stock: %d\n", books[i].stock);
printf("\n");
}
}
int main(void) {
int choice;
do {
printf("1. Add book\n");
printf("2. Search book\n");
printf("3. Print all books\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar();
switch (choice) {
case 1:
add_book();
break;
case 2:
search_book();
break;
case 3:
print_books();
break;
case 4:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice.\n");
break;
}
} while (choice != 4);
return 0;
}
```
这个例子中,我们定义了一个Book结构体来存储图书信息,包括书名、作者、出版社、出版日期和库存。我们还定义了一个数组books来存储所有的图书信息,以及一个变量num_books来记录当前存储的图书数量。
在主函数中,我们使用一个do-while循环来接受用户输入并执行相应的操作。用户可以选择添加新的图书信息、查询现有的图书信息或打印所有的图书信息。在添加新的图书信息时,我们使用fgets函数来接受包含空格的输入,并使用strcspn函数来去掉输入中的换行符。在查询图书信息时,我们使用strcmp函数来比较输入的书名和存储的书名是否相同。
需要注意的是,这个例子仅涉及基本功能,实际的图书管理系统需要考虑更多的功能和复杂性,例如借阅和归还、用户信息管理、统计分析等。