用c语言写图书管理系统
时间: 2023-12-08 13:56:05 浏览: 14
好的,以下是一个简单的图书管理系统的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
struct book {
char title[50];
char author[50];
int id;
};
struct library {
struct book books[MAX_BOOKS];
int count;
};
void add_book(struct library *lib, char *title, char *author, int id) {
if (lib->count < MAX_BOOKS) {
struct book *b = &(lib->books[lib->count]);
strcpy(b->title, title);
strcpy(b->author, author);
b->id = id;
lib->count++;
} else {
printf("Error: Library is full\n");
}
}
void remove_book(struct library *lib, int id) {
int index = -1;
for (int i = 0; i < lib->count; i++) {
if (lib->books[i].id == id) {
index = i;
break;
}
}
if (index != -1) {
for (int i = index; i < lib->count - 1; i++) {
lib->books[i] = lib->books[i+1];
}
lib->count--;
} else {
printf("Error: Book not found\n");
}
}
void list_books(struct library *lib) {
for (int i = 0; i < lib->count; i++) {
struct book *b = &(lib->books[i]);
printf("%d: %s by %s\n", b->id, b->title, b->author);
}
}
int main() {
struct library lib = {0};
char choice;
char title[50], author[50];
int id;
do {
printf("Enter choice (a=Add book, r=Remove book, l=List books, q=Quit): ");
choice = getchar();
getchar(); // consume newline character
switch (choice) {
case 'a':
printf("Enter book title: ");
fgets(title, sizeof(title), stdin);
title[strlen(title)-1] = '\0'; // remove newline character
printf("Enter book author: ");
fgets(author, sizeof(author), stdin);
author[strlen(author)-1] = '\0'; // remove newline character
printf("Enter book ID: ");
scanf("%d", &id);
getchar(); // consume newline character
add_book(&lib, title, author, id);
break;
case 'r':
printf("Enter book ID: ");
scanf("%d", &id);
getchar(); // consume newline character
remove_book(&lib, id);
break;
case 'l':
list_books(&lib);
break;
case 'q':
break;
default:
printf("Invalid choice\n");
break;
}
} while (choice != 'q');
return 0;
}
```
这个程序使用了结构体来表示图书和图书馆,并提供了添加、删除和列出图书的功能。您可以根据实际需要进行修改和扩展。