我想用switch语句来实现小甲鱼图书管理系统,为什么不可以?下面是我的代码,
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
struct library
{
char bookname;
char author;
struct library* next;
};
void addbook(struct library** first);
void printbook(struct library* first);
void releasespace(struct library** first);
int main()
{
struct library* first = NULL;
int ch;
printf("1添加图书\n");
printf("2打印图书\n");
printf("3退出\n");
while (1)
{
do
{printf("输入选项");
scanf("%d", &ch);
switch(ch)
{case 1:
addbook(&first);
break;
case 2:
printbook(first);
break;}
} while (ch !=3);
}
releasespace(&first);
return 0;
}
void addbook(struct library** first)
{
struct library* book, * temp;
book = (struct library*)malloc(sizeof(struct library));
*first = (struct library*)malloc(sizeof(struct library));
printf("请输入需要添加图书的名字:");
scanf("%s", book->bookname);
printf("请输入图书作者:");
scanf("%s", book->author);
{
book->next=(*first)->next;
(*first)->next=book;
}
}
void printbook(struct library* first)
{
struct library* book;
book = first;
while (book != NULL)
{
printf("书的名字:%s", book->bookname);
printf("书的作者:%s", book->author);
book = book->next;
}
}
void releasespace(struct library** first)
{
struct library* temp;
while (*first != NULL)
{
temp = *first;
*first = (*first)->next;
free(temp);
}
}
执行完程序有毛病,我如果添加两次,第一次打印错误,但是第二次就对了,不知道怎么回事,求大佬指点
你这个 while(1) 多余了,导致退不出循环,因为 break 语句只能退出一层循环,即退出内层的 do-while 循环 #include<stdio.h>
#include<stdlib.h>
//#include<malloc.h>
struct library
{
char bookname;
char author;
struct library* next;
};
void addbook(struct library** first);
void printbook(struct library* first);
void releasespace(struct library** first);
int main()
{
struct library* first = NULL;
first = (struct library*)malloc(sizeof(struct library)); //在这里初始化就好了
int ch;
printf("1添加图书\n");
printf("2打印图书\n");
printf("3退出\n");
while (1)
{
do
{printf("输入选项");
scanf("%d", &ch);
switch(ch)
{case 1:
addbook(&first);
break;
case 2:
printbook(first);
break;}
} while (ch !=3);
}
releasespace(&first);
return 0;
}
void addbook(struct library** first)
{
struct library* book, * temp;
book = (struct library*)malloc(sizeof(struct library));
// *first = (struct library*)malloc(sizeof(struct library)); 每次进来都你都分配空间,相当于声明一个新变量
printf("请输入需要添加图书的名字:");
scanf("%s", book->bookname);
printf("请输入图书作者:");
scanf("%s", book->author);
book->next=(*first)->next;
(*first)->next=book;
}
void printbook(struct library* first)
{
struct library* book;
book = first->next;//头指针是空节点,要指向下一个
while (book != NULL)
{
printf("书的名字:%s", book->bookname);
printf("书的作者:%s", book->author);
book = book->next;
}
}
void releasespace(struct library** first)
{
struct library* temp;
while (*first != NULL)
{
temp = *first;
*first = (*first)->next;
free(temp);
}
}
页:
[1]