c语言写 you have been assigned the task of computerizing the card catalog system for a library
时间: 2024-06-04 16:13:56 浏览: 16
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 1000 // maximum number of books in the library
struct book {
char title[50];
char author[50];
char publisher[50];
int year;
};
struct book library[MAX_BOOKS]; // array of books in the library
int numBooks = 0; // number of books in the library
void addBook() {
struct book newBook;
printf("Enter the book title: ");
fgets(newBook.title, 50, stdin);
printf("Enter the book author: ");
fgets(newBook.author, 50, stdin);
printf("Enter the book publisher: ");
fgets(newBook.publisher, 50, stdin);
printf("Enter the year of publication: ");
scanf("%d", &newBook.year);
getchar(); // clear input buffer
library[numBooks] = newBook;
numBooks++;
printf("Book added to the library.\n");
}
void searchBooks() {
char keyword[50];
printf("Enter a keyword to search for: ");
fgets(keyword, 50, stdin);
printf("Search results:\n");
int found = 0;
for (int i = 0; i < numBooks; i++) {
if (strstr(library[i].title, keyword) || strstr(library[i].author, keyword) || strstr(library[i].publisher, keyword)) {
printf("%d. %s by %s (%s, %d)\n", i+1, library[i].title, library[i].author, library[i].publisher, library[i].year);
found = 1;
}
}
if (!found) {
printf("No books found.\n");
}
}
void printLibrary() {
printf("Library catalog:\n");
for (int i = 0; i < numBooks; i++) {
printf("%d. %s by %s (%s, %d)\n", i+1, library[i].title, library[i].author, library[i].publisher, library[i].year);
}
}
int main() {
int choice;
do {
printf("Library card catalog system\n");
printf("1. Add a book\n");
printf("2. Search for a book\n");
printf("3. Print library catalog\n");
printf("4. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // clear input buffer
switch (choice) {
case 1:
addBook();
break;
case 2:
searchBooks();
break;
case 3:
printLibrary();
break;
case 4:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice.\n");
break;
}
} while (choice != 4);
return 0;
}