c语言程序设计图书管理系统
时间: 2023-08-29 13:11:54 浏览: 80
以下是一个简单的基于C语言的图书管理系统:
```c
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
struct book {
char title[100];
char author[100];
int year;
};
int num_books = 0;
struct book books[MAX_BOOKS];
void print_menu() {
printf("Welcome to the Book Management System!\n");
printf("1. Add a book\n");
printf("2. Search for a book\n");
printf("3. Print all books\n");
printf("4. Exit\n");
}
void add_book() {
if (num_books >= MAX_BOOKS) {
printf("Sorry, the maximum number of books has been reached.\n");
return;
}
struct book new_book;
printf("Enter the title of the book: ");
fgets(new_book.title, 100, stdin);
new_book.title[strlen(new_book.title) - 1] = '\0';
printf("Enter the author of the book: ");
fgets(new_book.author, 100, stdin);
new_book.author[strlen(new_book.author) - 1] = '\0';
printf("Enter the year the book was published: ");
scanf("%d", &new_book.year);
getchar();
books[num_books] = new_book;
num_books++;
printf("The book has been added to the system.\n");
}
void search_book() {
char search_title[100];
printf("Enter the title of the book to search for: ");
fgets(search_title, 100, stdin);
search_title[strlen(search_title) - 1] = '\0';
int found = 0;
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].title, search_title) == 0) {
printf("Book found:\n");
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Year: %d\n", books[i].year);
found = 1;
break;
}
}
if (!found) {
printf("Book not found.\n");
}
}
void print_all_books() {
printf("All books in the system:\n");
for (int i = 0; i < num_books; i++) {
printf("Book %d:\n", i+1);
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Year: %d\n", books[i].year);
}
}
int main() {
int choice;
do {
print_menu();
printf("Enter your choice: ");
scanf("%d", &choice);
getchar();
switch (choice) {
case 1:
add_book();
break;
case 2:
search_book();
break;
case 3:
print_all_books();
break;
case 4:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice, please try again.\n");
break;
}
} while (choice != 4);
return 0;
}
```
该程序使用结构体来存储书籍的信息,可以添加、搜索和打印所有书籍。用户可以通过菜单选择要执行的操作。程序限制了最大书籍数量为100本。
阅读全文