用c语言帮我写一个图书管理系统的代码
时间: 2023-08-28 11:13:57 浏览: 88
好的,下面是一个简单的图书管理系统的C语言代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
struct Book {
int id;
char title[50];
char author[50];
int year;
};
struct Book books[MAX_BOOKS];
int num_books = 0;
void add_book() {
struct Book book;
printf("Enter book title: ");
scanf("%s", book.title);
printf("Enter book author: ");
scanf("%s", book.author);
printf("Enter book year: ");
scanf("%d", &book.year);
book.id = num_books + 1;
books[num_books++] = book;
printf("Book added successfully.\n");
}
void list_books() {
printf("ID TITLE AUTHOR YEAR\n");
printf("--------------------------------------------------------------------\n");
for (int i = 0; i < num_books; ++i) {
printf("%-4d%-30s%-30s%-4d\n", books[i].id, books[i].title, books[i].author, books[i].year);
}
}
void search_books() {
char query[50];
printf("Enter search query: ");
scanf("%s", query);
printf("ID TITLE AUTHOR YEAR\n");
printf("--------------------------------------------------------------------\n");
for (int i = 0; i < num_books; ++i) {
if (strstr(books[i].title, query) || strstr(books[i].author, query)) {
printf("%-4d%-30s%-30s%-4d\n", books[i].id, books[i].title, books[i].author, books[i].year);
}
}
}
int main() {
int choice;
while (1) {
printf("\n");
printf("1. Add book\n");
printf("2. List books\n");
printf("3. Search books\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
list_books();
break;
case 3:
search_books();
break;
case 4:
printf("Goodbye!\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
```
这个代码实现了一个简单的图书管理系统,可以添加、列出和搜索图书。你可以根据自己的需求进行修改和扩展。
阅读全文