图书管理系统数组C语言
时间: 2023-11-24 10:51:07 浏览: 66
以下是一个简单的图书管理系统的C语言数组实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
struct Book {
char id[20];
char title[100];
char author[50];
float price;
int borrowed;
};
struct Book books[MAX_BOOKS];
int num_books = 0;
void add_book() {
if (num_books >= MAX_BOOKS) {
printf("Error: too many books\n");
return;
}
struct Book book;
printf("Enter book id: ");
scanf("%s", book.id);
printf("Enter book title: ");
scanf("%s", book.title);
printf("Enter book author: ");
scanf("%s", book.author);
printf("Enter book price: ");
scanf("%f", &book.price);
book.borrowed = 0;
books[num_books++] = book;
printf("Book added successfully\n");
}
void list_books() {
printf("ID\tTitle\tAuthor\tPrice\tBorrowed\n");
for (int i = 0; i < num_books; i++) {
printf("%s\t%s\t%s\t%.2f\t%s\n", books[i].id, books[i].title, books[i].author, books[i].price, books[i].borrowed ? "Yes" : "No");
}
}
void borrow_book() {
char id[20];
printf("Enter book id: ");
scanf("%s", id);
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].id, id) == 0) {
if (books[i].borrowed) {
printf("Error: book already borrowed\n");
} else {
books[i].borrowed = 1;
printf("Book borrowed successfully\n");
}
return;
}
}
printf("Error: book not found\n");
}
void return_book() {
char id[20];
printf("Enter book id: ");
scanf("%s", id);
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].id, id) == 0) {
if (!books[i].borrowed) {
printf("Error: book not borrowed\n");
} else {
books[i].borrowed = 0;
printf("Book returned successfully\n");
}
return;
}
}
printf("Error: book not found\n");
}
int main() {
int choice;
do {
printf("1. Add book\n");
printf("2. List books\n");
printf("3. Borrow book\n");
printf("4. Return book\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
list_books();
break;
case 3:
borrow_book();
break;
case 4:
return_book();
break;
case 5:
printf("Goodbye!\n");
break;
default:
printf("Error: invalid choice\n");
break;
}
} while (choice != 5);
return 0;
}
```