C Book Management System: Create a Library in C

You can use the C programming language to create a basic library management system. Below is a simple example code:

#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;
}

This code segment creates a basic library management system where users can choose to add books or display all books. The books are stored in an array of structures, allowing users to expand functionality like deleting books or searching for books based on their needs.

bannerAds