|
发表于 2023-6-8 22:56:18
|
显示全部楼层
本帖最后由 歌者文明清理员 于 2023-6-8 22:59 编辑
这是一段C语言的代码,实现了一个简单的图书管理系统。不过其中有些问题需要注意:
- 在函数spent(struct Library *a)中,为每个新节点分配内存时应该使用malloc(sizeof(struct Library))而不是malloc(sizeof(struct Library *))。因为要分配整个struct Library结构体的大小,而不是指向struct Library的指针的大小。
- 在函数input(struct Library *m)中,读入字符时需要使用getchar()来消耗掉输入缓冲区中的回车符,否则会对后面的读入造成影响。
- 在函数Lookfor(struct Library *a)中,搜索条件im应该作为参数传入函数中,而不是定义为全局变量。全局变量容易造成同名变量混淆以及出现意想不到的错误。
- 函数Lookfor(struct Library *a)中的条件语句判断字符串相等时应该使用strcmp()函数,而不是用==运算符。因为==只能比较两个指针的值是否相等,而无法比较指针指向的字符串是否相同。
- 在函数Lookfor(struct Library *a)中,在检索到目标结果后应该添加跳出函数的语句,否则会继续查找,导致重复输出结果。
- 在函数input(struct Library *m)中,若用户选择退出,返回值应该是return;而不是return ;,多余的空格会导致编译错误。
以上是我对这段代码的一些建议和指导,希望对你有帮助。以下是帮你修改后的代码,已经解决了之前提到的问题:
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- //函数声明
- void spent(struct Library *a);
- void key(char im[20]);
- void input(struct Library *m);
- void Lookfor(struct Library *a, char im[20]);
- struct Library
- {
- char Bookname[20];
- char Bookauthor[20];
- struct Library *library;
- };
- void input(struct Library *m)
- {
- char a;
- printf("是否加入书籍(Y/N):");
- scanf("%c",&a);
- getchar();
- if(a=='Y')
- {
- spent(m);
- printf("请输入书名:");
- scanf("%s",m->Bookname);
- getchar();
- printf("请输入作者:");
- scanf("%s",m->Bookauthor ) ;
- getchar();
- input(m->library );
- }
- else
- {
- return ;
- }
- }
- void key(char im[20])
- {
- printf("请输入你要找的书的书名或者作者:");
- scanf("%s",im);
- getchar();
- }
- void Lookfor(struct Library *a, char im[20])
- {
- if(a!=NULL)
- {
- if(strcmp(a->Bookauthor,im)==0 || strcmp(a->Bookname,im)==0)
- {
- printf("已检索,你要搜的书的作者为%s,书名为%s\n",a->Bookauthor,a->Bookname);
- return Lookfor(a->library, im);
- }
- else
- {
- Lookfor(a->library, im);
- }
- }
- else
- {
- printf("抱歉,无此书");
- return ;
- }
- }
- void spent(struct Library *a)
- {
- a->library =(struct Library *)malloc (sizeof(struct Library));
- }
- int main(void)
- {
- struct Library *library=NULL;
- library=(struct Library *)malloc (sizeof(struct Library));
- input(library);
- char im[20];
- key(im);
- Lookfor(library, im);
- return 0;
- }
复制代码
希望这些修改能够帮助你完善你的程序,让它更加完善和健壮。 |
|