用c语言写一个图书管理系统
时间: 2023-12-11 09:48:37 浏览: 30
好的,下面是一个简单的图书管理系统的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
struct book {
char title[50];
char author[50];
int year;
int pages;
float price;
};
struct book books[MAX_BOOKS];
int num_books = 0;
void display_menu() {
printf("\n");
printf("1. Add book\n");
printf("2. Display all books\n");
printf("3. Search book by title\n");
printf("4. Quit\n");
printf("\n");
}
void add_book() {
struct book new_book;
printf("Enter book title: ");
scanf("%s", new_book.title);
printf("Enter author name: ");
scanf("%s", new_book.author);
printf("Enter year of publication: ");
scanf("%d", &new_book.year);
printf("Enter number of pages: ");
scanf("%d", &new_book.pages);
printf("Enter price: ");
scanf("%f", &new_book.price);
books[num_books] = new_book;
num_books++;
printf("Book added successfully.\n");
}
void display_books() {
int i;
printf("Title\tAuthor\tYear\tPages\tPrice\n");
for (i = 0; i < num_books; i++) {
printf("%s\t%s\t%d\t%d\t%.2f\n", books[i].title,
books[i].author, books[i].year, books[i].pages,
books[i].price);
}
}
void search_book_by_title() {
char title[50];
int i;
printf("Enter book title: ");
scanf("%s", title);
for (i = 0; i < num_books; i++) {
if (strcmp(books[i].title, title) == 0) {
printf("Title\tAuthor\tYear\tPages\tPrice\n");
printf("%s\t%s\t%d\t%d\t%.2f\n", books[i].title,
books[i].author, books[i].year, books[i].pages,
books[i].price);
return;
}
}
printf("Book not found.\n");
}
int main() {
int choice;
do {
display_menu();
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
display_books();
break;
case 3:
search_book_by_title();
break;
case 4:
printf("Thank you for using the system.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
break;
}
} while (choice != 4);
return 0;
}
```
这个程序使用结构体 `book` 来表示一本书,定义了一个数组 `books` 来存储所有的书,最多存储 `MAX_BOOKS` 本书。程序提供了添加书籍、显示所有书籍和按书名搜索书籍三个功能。运行程序后,会显示一个菜单,用户根据需要选择相应的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)