struct Books_list { int id; //书号 char name[30]; //书名 char author[30]; //作者 char press[30]; //出版社名 }; struct Books_list book1[MAX_BOOKS]={ {1,"唐诗三百首","孙洙","南京大学出版社"}, {2,"三体","刘慈欢","北美权威科幻类出版社"}, {3,"稻草人","叶圣陶","湖南儿童出版社"}, {4,"老人与海","海明威","上海译文出版社"}, {5,"c语言","泰戈尔","浙江文艺出版社"}, };void addbook(struct Books_list book1) { struct Books_list BOOK; printf("序号:"); scanf("%s",BOOK.id); printf("书名:"); scanf("%s",BOOK.name); printf("作者:"); scanf("%s",BOOK.author); printf("出版社:"); scanf("%s",BOOK.press); book1[count++]=BOOK; printf("添加成功!\n"); }怎么修改这段代码
时间: 2023-07-18 11:53:30 浏览: 102
这段代码存在以下问题:
1. scanf("%s",BOOK.id)应该改为scanf("%d",&BOOK.id),因为id是整型,需要用%d进行格式化输入。
2. count变量没有定义,需要在函数外部定义一个全局变量int count=5;来记录已有的书籍数量。
3. addbook()函数中的book1是一个数组名,不能作为参数传递,否则会退化为指针类型。正确的写法应该是传递一个Books_list类型的结构体参数,例如:void addbook(struct Books_list newbook)。
修改后的代码如下:
```c
#define MAX_BOOKS 100
struct Books_list {
int id; //书号
char name[30]; //书名
char author[30]; //作者
char press[30]; //出版社名
};
struct Books_list book1[MAX_BOOKS] = {
{1, "唐诗三百首", "孙洙", "南京大学出版社"},
{2, "三体", "刘慈欢", "北美权威科幻类出版社"},
{3, "稻草人", "叶圣陶", "湖南儿童出版社"},
{4, "老人与海", "海明威", "上海译文出版社"},
{5, "c语言", "泰戈尔", "浙江文艺出版社"}
};
int count = 5;
void addbook(struct Books_list newbook) {
printf("序号:");
scanf("%d", &newbook.id);
printf("书名:");
scanf("%s", newbook.name);
printf("作者:");
scanf("%s", newbook.author);
printf("出版社:");
scanf("%s", newbook.press);
book1[count++] = newbook;
printf("添加成功!\n");
}
```
阅读全文