1.(20分)图书馆的书对的数据类型定义如下: struct bo Error: expected a ? char name_of_book[100];./书名。 char author[25]; //作者 }; 编写函数实现:(1)统计某一作者编写了几本书。 (2)将所有书的记录存储到文件a.txt。 然后编写相应的主函数输入若干数据,并调用这两个函数实现相应功能。 程序运行结果示例:请输入书的数量:5 Please input 1 name_of_book and author : c zhao Please input 2 name_of_book and author: java li Please input 3 name_of book and author : c++ wang Please input 4 name_of_book and author: vb li Please input 5 name_of book and author : vc li 请输入作者的姓名并统计他编写书的数量: li li作者编写了3本书 a.txt文件内容为: NO.1czhao NO.2 java li NO.3 c++ wang NO.4vb li NO.5 vc li 输入提示:“请输入书的数量:\n”输入格式:%d 输入提示:"Please input %d name_of book and author:\n"输入格式:%s%s 输入提示:“请输入作者的姓名并统计他编写书的数量;\n"输入格式:%s a.txt文件中错误输出提示:"error!\n"
时间: 2024-03-12 13:43:43 浏览: 32
以下是代码实现,注释中有详细解释:
```c
#include <stdio.h>
#include <string.h>
//定义book结构体
struct book {
char name_of_book[100];
char author[25];
};
//统计某一作者编写了几本书
int count_books(struct book books[], int n, char author[]) {
int count = 0;
for (int i = 0; i < n; i++) {
if (strcmp(books[i].author, author) == 0) {
count++;
}
}
return count;
}
//将所有书的记录存储到文件a.txt
void save_books_to_file(struct book books[], int n) {
//打开文件a.txt,如果失败则输出错误信息并返回
FILE *fp = fopen("a.txt", "w");
if (fp == NULL) {
printf("error!\n");
return;
}
//循环遍历所有书,将它们的记录写入文件中
for (int i = 0; i < n; i++) {
fprintf(fp, "NO.%d %s %s\n", i + 1, books[i].name_of_book, books[i].author);
}
//关闭文件
fclose(fp);
}
int main() {
int n;
printf("请输入书的数量:\n");
scanf("%d", &n);
struct book books[n];
//循环输入每本书的书名和作者
for (int i = 0; i < n; i++) {
printf("Please input %d name_of book and author:\n", i + 1);
scanf("%s%s", books[i].name_of_book, books[i].author);
}
char author[25];
printf("请输入作者的姓名并统计他编写书的数量:\n");
scanf("%s", author);
int count = count_books(books, n, author);
printf("%s作者编写了%d本书\n", author, count);
save_books_to_file(books, n);
return 0;
}
```
注意:在保存到文件中时,每本书的记录格式为"NO.i 书名 作者",其中i为书的编号,从1开始。