實現一個簡單的圖書管理系統可以使用C語言來實現,以下是一個簡單的示例代碼:
#include <stdio.h>
#include <string.h>
// 定義圖書結構體
struct Book {
int id;
char title[50];
char author[50];
int year;
};
// 初始化圖書數組
struct Book library[100];
int num_books = 0;
// 添加圖書函數
void addBook() {
struct Book newBook;
printf("Enter book title: ");
scanf("%s", newBook.title);
printf("Enter book author: ");
scanf("%s", newBook.author);
printf("Enter publication year: ");
scanf("%d", &newBook.year);
newBook.id = num_books + 1;
library[num_books] = newBook;
num_books++;
printf("Book added successfully!\n");
}
// 顯示所有圖書函數
void showBooks() {
for (int i = 0; i < num_books; i++) {
printf("ID: %d\n", library[i].id);
printf("Title: %s\n", library[i].title);
printf("Author: %s\n", library[i].author);
printf("Year: %d\n", library[i].year);
printf("\n");
}
}
int main() {
int choice;
do {
printf("1. Add book\n");
printf("2. Show all books\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addBook();
break;
case 2:
showBooks();
break;
case 3:
printf("Exiting program...\n");
break;
default:
printf("Invalid choice. Try again.\n");
break;
}
} while (choice != 3);
return 0;
}
這段代碼實現了一個簡單的圖書管理系統,用戶可以選擇添加圖書或顯示所有圖書的功能。圖書被存儲在一個結構體數組中,用戶可以根據自己的需求擴展更多功能,比如刪除圖書、搜索圖書等。