用c语言写一个图书管理系统
时间: 2023-11-24 10:06:35 浏览: 59
好的,以下是一个基于C语言的简单图书管理系统的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
#define MAX_TITLE_LENGTH 50
struct Book {
char title[MAX_TITLE_LENGTH];
int year;
float price;
};
int num_books = 0;
struct Book library[MAX_BOOKS];
void add_book() {
if (num_books < MAX_BOOKS) {
struct Book new_book;
printf("Enter the title of the book: ");
scanf("%s", new_book.title);
printf("Enter the year of publication: ");
scanf("%d", &new_book.year);
printf("Enter the price of the book: ");
scanf("%f", &new_book.price);
library[num_books++] = new_book;
printf("Book added successfully!\n\n");
} else {
printf("Library is full. Cannot add more books.\n\n");
}
}
void display_books() {
if (num_books == 0) {
printf("No books in the library.\n\n");
} else {
printf("Books in the library:\n");
for (int i = 0; i < num_books; i++) {
printf("%d. %s, published in %d, price: $%.2f\n", i+1, library[i].title, library[i].year, library[i].price);
}
printf("\n");
}
}
void search_book() {
if (num_books == 0) {
printf("No books in the library.\n\n");
} else {
char search_title[MAX_TITLE_LENGTH];
printf("Enter the title of the book to search: ");
scanf("%s", search_title);
int found = 0;
for (int i = 0; i < num_books; i++) {
if (strcmp(library[i].title, search_title) == 0) {
printf("Book found:\n");
printf("%s, published in %d, price: $%.2f\n\n", library[i].title, library[i].year, library[i].price);
found = 1;
break;
}
}
if (!found) {
printf("Book not found.\n\n");
}
}
}
void delete_book() {
if (num_books == 0) {
printf("No books in the library.\n\n");
} else {
char delete_title[MAX_TITLE_LENGTH];
printf("Enter the title of the book to delete: ");
scanf("%s", delete_title);
int found = 0;
for (int i = 0; i < num_books; i++) {
if (strcmp(library[i].title, delete_title) == 0) {
for (int j = i; j < num_books - 1; j++) {
library[j] = library[j+1];
}
num_books--;
printf("Book deleted successfully!\n\n");
found = 1;
break;
}
}
if (!found) {
printf("Book not found.\n\n");
}
}
}
int main() {
int choice;
do {
printf("Select an option:\n");
printf("1. Add a book\n");
printf("2. Display all books\n");
printf("3. Search for a book\n");
printf("4. Delete a book\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
printf("\n");
switch (choice) {
case 1: add_book(); break;
case 2: display_books(); break;
case 3: search_book(); break;
case 4: delete_book(); break;
case 5: printf("Goodbye!"); break;
default: printf("Invalid choice. Please try again.\n\n");
}
} while (choice != 5);
return 0;
}
```
这个程序实现了以下功能:
1. 添加一本书:输入书名、出版年份、价格,添加到图书馆中;
2. 显示所有书籍:列出所有已添加到图书馆中的书籍;
3. 搜索一本书:输入书名,查找图书馆中是否有匹配的书籍;
4. 删除一本书:输入书名,从图书馆中删除匹配的书籍;
5. 退出程序:结束图书馆管理系统。
请注意,此示例程序仅供参考,实际应用中可能需要更复杂的功能和数据结构。
阅读全文