用C写一个图书管理系统,要求用户输入图书的各个信息,用户再输入0,代表查看信息,然后选择查看的id,然后输出该本书的信息,输入1代表录入一本书的信息,信息包括id号、书名、作者名、价格和数量等;系统的主要功能包括:图书信息的创建,保存图书信息.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Book {
int id;
char title[100];
char author[100];
float price;
int quantity;
};
struct BookManagementSystem {
struct Book* books;
int capacity;
int size;
};
struct BookManagementSystem* createBookManagementSystem(int capacity) {
struct BookManagementSystem* bms = (struct BookManagementSystem*)malloc(sizeof(struct BookManagementSystem));
bms->books = (struct Book*)malloc(capacity * sizeof(struct Book));
bms->capacity = capacity;
bms->size = 0;
return bms;
}
void addBook(struct BookManagementSystem* bms, int id, char* title, char* author, float price, int quantity) {
if (bms->size < bms->capacity) {
struct Book* newBook = &(bms->books[bms->size]);
newBook->id = id;
strcpy(newBook->title, title);
strcpy(newBook->author, author);
newBook->price = price;
newBook->quantity = quantity;
bms->size++;
} else {
printf("Book database is full. Cannot add more books.\n");
}
}
void displayBookInfo(struct BookManagementSystem* bms, int id) {
for (int i = 0; i < bms->size; i++) {
if (bms->books[i].id == id) {
printf("Book ID: %d\n", bms->books[i].id);
printf("Title: %s\n", bms->books[i].title);
printf("Author: %s\n", bms->books[i].author);
printf("Price: %.2f\n", bms->books[i].price);
printf("Quantity: %d\n", bms->books[i].quantity);
return;
}
}
printf("Book with ID %d not found.\n", id);
}
void saveBooksToFile(struct BookManagementSystem* bms, char* filename) {
FILE *file = fopen(filename, "w");
if (file != NULL) {
for (int i = 0; i < bms->size; i++) {
fprintf(file, "%d,%s,%s,%.2f,%d\n", bms->books[i].id, bms->books[i].title, bms->books[i].author, bms->books[i].price, bms->books[i].quantity);
}
fclose(file);
} else {
printf("Unable to open file for writing.\n");
}
}
int main() {
struct BookManagementSystem* bms = createBookManagementSystem(10);
int choice;
int id;
char title[100];
char author[100];
float price;
int quantity;
while (1) {
printf("Enter 0 to view book information, enter 1 to add a new book, or any other number to exit: ");
scanf("%d", &choice);
if (choice == 0) {
printf("Enter the book ID to view: ");
scanf("%d", &id);
displayBookInfo(bms, id);
} else if (choice == 1) {
printf("Enter book ID: ");
scanf("%d", &id);
printf("Enter title: ");
scanf("%s", title);
printf("Enter author: ");
scanf("%s", author);
printf("Enter price: ");
scanf("%f", &price);
printf("Enter quantity: ");
scanf("%d", &quantity);
addBook(bms, id, title, author, price, quantity);
} else {
break;
}
}
saveBooksToFile(bms, "books.txt");
free(bms->books);
free(bms);
return 0;
}