图书馆的书对应的数据类型定义如下: struct book { char name_of_book[100]; //书名 char author[25]; //作者 }; 编写函数实现: (1)统计某一作者编写了几本书。 (2)将所有书的记录存储到文件a.txt。 然后编写相应的主函数输入若干数据,并调用这两个函数实现相应 功能。用C语言实现
时间: 2023-12-18 10:03:08 浏览: 149
以下是实现代码:
```c
#include <stdio.h>
#include <string.h>
struct book {
char name_of_book[100];
char author[25];
};
// 统计某一作者编写了几本书
int count_book_by_author(struct book *books, int size, char *author) {
int count = 0;
for (int i = 0; i < size; i++) {
if (strcmp(books[i].author, author) == 0) {
count++;
}
}
return count;
}
// 将所有书的记录存储到文件a.txt
void save_books_to_file(struct book *books, int size) {
FILE *fp = fopen("a.txt", "w");
if (fp == NULL) {
printf("Failed to create file!\n");
return;
}
for (int i = 0; i < size; i++) {
fprintf(fp, "%s %s\n", books[i].name_of_book, books[i].author);
}
fclose(fp);
}
int main() {
struct book books[100];
int size = 0;
// 输入书籍信息
printf("Please enter the book information (\"exit\" to quit):\n");
while (1) {
printf("Book name: ");
fgets(books[size].name_of_book, 100, stdin);
books[size].name_of_book[strcspn(books[size].name_of_book, "\n")] = 0;
if (strcmp(books[size].name_of_book, "exit") == 0) {
break;
}
printf("Author: ");
fgets(books[size].author, 25, stdin);
books[size].author[strcspn(books[size].author, "\n")] = 0;
size++;
}
// 统计某一作者编写了几本书
char author[25];
printf("Please enter the author name: ");
fgets(author, 25, stdin);
author[strcspn(author, "\n")] = 0;
int count = count_book_by_author(books, size, author);
printf("%s has written %d books.\n", author, count);
// 将所有书的记录存储到文件a.txt
save_books_to_file(books, size);
return 0;
}
```
其中,`fgets()` 函数用于读取用户输入的字符串,`strcspn()` 函数用于去掉字符串末尾的换行符。`count_book_by_author()` 函数使用了 `strcmp()` 函数来比较作者名字是否相同,`save_books_to_file()` 函数使用了 `fprintf()` 函数来向文件中写入数据。
阅读全文