这代码是那错了,怎么只能输出第一本书,就很头疼,编译没问题,用的Vc++6.0
本帖最后由 cyn.c 于 2022-3-29 19:26 编辑这代码是那错了,怎么只能输出第一本书,就很头疼,编译没问题,用的Vc++6.0
#include<stdio.h>
#include<stdlib.h>
struct Book
{
char title;
char author;
struct Book *next;
};
void printlibrary(struct Book *library);
void getInput(struct Book *book);
void addBook(struct Book **library);
void releaselibrary(struct Book *library);
void printlibrary(struct Book *library)
{
struct Book *book;
int count=1;
book=library;
if(book!=NULL)
{
printf("book%d:",count);
printf("书名:%s\n",book->title);
printf("作者:%s\n",book->author);
book=book->next;
count++;
}
}
void getInput(struct Book *book)
{
printf("请输入书名:");
scanf("%s",book->title);
printf("请输入作者:");
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)
{
temp=*library;
*library=book;
book->next=temp;
}
else
{
*library=book;
book->next=NULL;
}
}
void releaselibrary(struct Book *library)
{
while(library!=NULL)
{
library=library->next;
free(library);
}
}
int main(void)
{
struct Book *library=NULL;
int ch;
while(1)
{
printf("是否需要录入书籍信息(Y/N):");
do
{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y')
{
addBook(&library);
}
else
{
break;
}
}
printf("是否需要打印书籍信息(Y/N):");
do
{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y')
{
printlibrary(library);
}
releaselibrary(library);
return 0;
} #include<stdio.h>
#include<stdlib.h>
struct Book
{
char title;
char author;
struct Book *next;
};
void printlibrary(struct Book *library)
{
struct Book *book;
int count=1;
book=library;
while(book!=NULL) // while
{
printf("book%d:",count);
printf("书名:%s\n",book->title);
printf("作者:%s\n",book->author);
book=book->next;
count++;
}
}
void getInput(struct Book *book)
{
printf("请输入书名:");
scanf("%s",book->title);
printf("请输入作者:");
scanf("%s",book->author);
}
void addBook(struct Book **library)
{
struct Book *book;
book=(struct Book *)malloc(sizeof(struct Book));
if(book==NULL)
{
printf("内存分配失败!");
exit(1);
}
getInput(book);
// 按你的思路这里使用的应该是 头插法
if(*library!=NULL)
{
book->next=*library;
*library = book;
}
else
{
*library=book;
book->next=NULL;
}
}
void releaselibrary(struct Book *library)
{
struct Book *temp;
while(library!=NULL)
{
// 释放顺序
temp = library->next;
free(library);
library=temp;
}
}
int main(void)
{
struct Book *library=NULL;
int ch;
while(1)
{
printf("是否需要录入书籍信息(Y/N):");
do
{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y')
{
addBook(&library);
}
else
{
break;
}
}
printf("是否需要打印书籍信息(Y/N):");
do
{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y')
{
printlibrary(library);
}
releaselibrary(library);
return 0;
} ba21 发表于 2022-3-29 19:54
谢谢哥们,可以了
页:
[1]