c语言编写图书管理系统
时间: 2023-07-13 17:37:11 浏览: 113
好的,下面是一份用C语言编写的图书管理系统代码,仅供参考:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 1000
#define MAX_NAME_LENGTH 50
#define MAX_AUTHOR_LENGTH 50
#define MAX_PUBLISHER_LENGTH 50
struct Book {
char name[MAX_NAME_LENGTH];
char author[MAX_AUTHOR_LENGTH];
char publisher[MAX_PUBLISHER_LENGTH];
int year;
int price;
};
struct Library {
struct Book books[MAX_BOOKS];
int numBooks;
};
void addBook(struct Library *library) {
struct Book newBook;
printf("Please enter the book name: ");
fgets(newBook.name, MAX_NAME_LENGTH, stdin);
printf("Please enter the author: ");
fgets(newBook.author, MAX_AUTHOR_LENGTH, stdin);
printf("Please enter the publisher: ");
fgets(newBook.publisher, MAX_PUBLISHER_LENGTH, stdin);
printf("Please enter the year of publication: ");
scanf("%d", &newBook.year);
printf("Please enter the price: ");
scanf("%d", &newBook.price);
getchar(); // consume the newline character
library->books[library->numBooks++] = newBook;
printf("Book added successfully!\n");
}
void removeBook(struct Library *library) {
printf("Please enter the book name to remove: ");
char searchName[MAX_NAME_LENGTH];
fgets(searchName, MAX_NAME_LENGTH, stdin);
for (int i = 0; i < library->numBooks; i++) {
if (strcmp(searchName, library->books[i].name) == 0) {
for (int j = i; j < library->numBooks - 1; j++) {
library->books[j] = library->books[j + 1];
}
library->numBooks--;
printf("Book removed successfully!\n");
return;
}
}
printf("Book not found!\n");
}
void displayBooks(struct Library *library) {
printf("Library contains %d books:\n", library->numBooks);
for (int i = 0; i < library->numBooks; i++) {
printf("%s, by %s, published by %s in %d, price: %d\n",
library->books[i].name, library->books[i].author,
library->books[i].publisher, library->books[i].year,
library->books[i].price);
}
}
void menu(struct Library *library) {
while (1) {
printf("\nPlease select an option:\n");
printf("1. Add a book\n");
printf("2. Remove a book\n");
printf("3. Display all books\n");
printf("4. Quit\n");
int choice;
scanf("%d", &choice);
getchar(); // consume the newline character
switch (choice) {
case 1:
addBook(library);
break;
case 2:
removeBook(library);
break;
case 3:
displayBooks(library);
break;
case 4:
return;
default:
printf("Invalid option!\n");
break;
}
}
}
int main() {
struct Library library = {0};
menu(&library);
return 0;
}
```
这份代码实现了一个简单的图书管理系统,包括添加书籍、删除书籍和显示所有书籍等功能。需要注意的是,这份代码中使用了结构体来表示书籍和图书馆,方便进行管理。同时,也使用了循环、条件语句和函数等基本的C语言语法。