C語(yǔ)言怎么實(shí)現(xiàn)簡(jiǎn)單的圖書管理系統(tǒng)

小億
142
2024-03-08 14:46:28

實(shí)現(xiàn)一個(gè)簡(jiǎn)單的圖書管理系統(tǒng)可以使用C語(yǔ)言來(lái)實(shí)現(xiàn),以下是一個(gè)簡(jiǎn)單的示例代碼:

#include <stdio.h>
#include <string.h>

// 定義圖書結(jié)構(gòu)體
struct Book {
    int id;
    char title[50];
    char author[50];
    int year;
};

// 初始化圖書數(shù)組
struct Book library[100];
int num_books = 0;

// 添加圖書函數(shù)
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");
}

// 顯示所有圖書函數(shù)
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;
}

這段代碼實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的圖書管理系統(tǒng),用戶可以選擇添加圖書或顯示所有圖書的功能。圖書被存儲(chǔ)在一個(gè)結(jié)構(gòu)體數(shù)組中,用戶可以根據(jù)自己的需求擴(kuò)展更多功能,比如刪除圖書、搜索圖書等。

1