以下是一个简单的C语言图书管理系统的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
#define MAX_TITLE 100
#define MAX_AUTHOR 100
typedef struct {
int id;
char title[MAX_TITLE];
char author[MAX_AUTHOR];
int available;
} Book;
Book library[MAX_BOOKS];
int book_count = 0;
void add_book() {
if (book_count >= MAX_BOOKS) {
printf("Library is full!n");
return;
}
printf("Enter book title: ");
getchar(); // to consume newline character from previous input
fgets(library[book_count].title, MAX_TITLE, stdin);
library[book_count].title[strcspn(library[book_count].title, "n")] = '';
printf("Enter book author: ");
fgets(library[book_count].author, MAX_AUTHOR, stdin);
library[book_count].author[strcspn(library[book_count].author, "n")] = '';
library[book_count].id = book_count + 1;
library[book_count].available = 1;
book_count++;
printf("Book added successfully!n");
}
void display_books() {
if (book_count == 0) {
printf("No books in the library.n");
return;
}
printf("IDtTitlettAuthorttAvailablen");
for (int i = 0; i < book_count; i++) {
printf("%dt%stt%stt%sn", library[i].id, library[i].title, library[i].author, library[i].available ? "Yes" : "No");
}
}
void borrow_book() {
int id;
printf("Enter book ID to borrow: ");
scanf("%d", &id);
if (id > 0 && id <= book_count && library[id - 1].available) {
library[id - 1].available = 0;
printf("You have borrowed the book: %sn", library[id - 1].title);
} else {
printf("Book not available.n");
}
}
void return_book() {
int id;
printf("Enter book ID to return: ");
scanf("%d", &id);
if (id > 0 && id <= book_count && !library[id - 1].available) {
library[id - 1].available = 1;
printf("You have returned the book: %sn", library[id - 1].title);
} else {
printf("Invalid book ID.n");
}
}
int main() {
int choice;
while (1) {
printf("nLibrary Management Systemn");
printf("1. Add Bookn");
printf("2. Display Booksn");
printf("3. Borrow Bookn");
printf("4. Return Bookn");
printf("5. Exitn");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
display_books();
break;
case 3:
borrow_book();
break;
case 4:
return_book();
break;
case 5:
exit(0);
default:
printf("Invalid choice, please try again.n");
}
}
return 0;
}
该系统包括以下功能:
- 添加图书
- 显示图书列表
- 借阅图书
- 归还图书
运行该程序时,用户可以通过菜单选择不同的功能。图书信息包括图书编号、标题、作者和是否可用状态。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/190864.html