scanf运行时程序退出
本帖最后由 wzppp 于 2022-4-28 00:56 编辑学习链表头插法,怎么每次输入书名后,弹出”请输入作者“等待2s大概,程序就结束了,这是什么原因?
输出情况:
是否录入书籍信息(Y/N):Y
请输入书名:SSS
请输入作者:
struct Book
{
char title;
char author;
struct Book *next;
};
void getInput(struct Book *book)//输入书籍信息
{
printf("请输入书名:");
scanf("%s\n",book->title);
printf("请输入作者:");
scanf("%s\n",book->author);
}
void addBook(struct Book **library)
{
struct Book *book,*temp;
book = (struct Book *)malloc(sizeof(struct Book));
if(book = NULL)
{
printf("内存分配失败!\n");
exit(1);
}
getInput(book);
if(*library != NULL)
{
temp=*library;
*library = book;
book->next = temp;
}
else
{
*library = book;
book->next = NULL;
}
}
void printLib(struct Book *library)//打印书籍信息
{
struct Book *book;
int count = 1;
book = library;
while (book != NULL)
{
printf("Book%d:",count);
printf("书籍名称:%s:\n",book->title);
printf("作者:%s:\n",book->author);
book=book->next;
count++;
}
}
void releaseLib(struct Book *library)
{
while(library != NULL)
{
free(library);
library=library->next;
}
}
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')
{
printLib(library);
}
releaseLib(library);
return 0;
} printf("请输入书名:");
scanf("%s\n",book->title);
printf("请输入作者:");
scanf("%s\n",book->author);
把这两个\n去掉,谁教你这样写的 wp231957 发表于 2022-4-28 08:08
printf("请输入书名:");
scanf("%s\n",book->title);
printf("请输入作者:");
感谢! 找到了,话有个主要问题是在分配完空间后,if条件写了一个等号,不是判断语句,错了。
页:
[1]