|
发表于 2023-7-19 20:46:44
|
显示全部楼层
本楼为最佳答案

你的代码有几个问题,包括语法错误和逻辑错误。下面是一些修改后的代码:
- #include<stdio.h>
- #include<stdlib.h>
- struct Book{
- char title[100];
- char author[40];
- struct Book *next;
- };
- void getInput(struct Book *book);
- void addBook(struct Book **library);
- void bookPrint(struct Book *library);
- void releaseLibrary(struct Book **library);
- void getInput(struct Book *book)
- {
- printf("请输入书名:\n");
- scanf("%s",book->title);
- printf("请输入作者:\n");
- scanf("%s",book->author);
- }
- void addBook(struct Book **library)
- {
- struct Book *book,*temp;
- book = (struct Book *)malloc(sizeof(struct Book));
- if(book == NULL)
- {
- printf("分配内存空间失败!");
- exit(1);
- }
- getInput(book);
- if(*library == NULL)
- {
- *library = book;
- book->next = NULL;
- }
- else
- {
- temp = *library;
- *library = book;
- book->next = temp;
- }
- }
- void bookPrint(struct Book *library)
- {
- struct Book *book;
- book = library;
- int count = 1;
- while(book != NULL)
- {
- printf("第%d本书\n",count);
- printf("书名: %s\n",book->title);
- printf("作者: %s\n",book->author);
- book = book->next;
- count++;
- }
- }
- void releaseLibrary(struct Book **library)
- {
- struct Book *temp;
- while(*library != NULL)
- {
- temp = *library;
- *library = (*library)->next;
- free(temp);
- }
- }
- int main()
- {
- struct Book *library = NULL;
- char ch;
- addBook(&library);
- while(1)
- {
- printf("是否添加书籍?:(Y/N)");
- scanf(" %c", &ch);
- if(ch == 'Y' || ch == 'y')
- addBook(&library);
- else if(ch == 'N' || ch == 'n')
- break;
- printf("是否打印?:(Y/N)");
- scanf(" %c", &ch);
- if(ch == 'Y' || ch == 'y')
- bookPrint(library);
- else if(ch == 'N' || ch == 'n')
- break;
- }
- releaseLibrary(&library);
- return 0;
- }
复制代码
修复了的问题包括:
1. addBook 函数的结束括号丢失。
2. if(book = NULL) 修改为 if(book == NULL) , = 是赋值操作, == 是比较操作。
3. bookPrint 和 printf 函数的参数不正确。
4. releaseLibrary 函数的参数应该是双指针,因为你要修改指针本身。
5. getchar() 函数通常会从缓冲区中读取一个字符,如果缓冲区中没有字符,它将等待用户输入。为了避免读取上一次残留的换行符,使用 scanf(" %c", &ch); 是个好方法。
6. 主函数的循环逻辑错误,你的 while 和 do-while 混合使用,可能造成一些逻辑问题,所以我对这部分进行了修正。 |
|