|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<winuser.inl>
- #include<stdio.h>
- #include <cstdlib>
- #include<string.h>
- //输入学生以及每个学生的姓名成绩
- //输入学生姓名,显示成绩,
- //用头插法向链表里面添加元素
- void getInput(struct Student* stu);
- void printfInfo(struct Student* head);
- void releaseMemory(struct Student** head);
- void head_add(struct Student** head);
- struct Student
- {
- char name[20];
- int score;
- struct Student* next;
- };
- void getInput(struct Student* stu)
- {
- printf("name:");
- scanf_s("%s", stu->name, 20);
- printf("score:");
- scanf_s("%d", &stu->score);
- }
- void printfInfo(struct Student *head)
- {
- struct Student* stu;
- stu = head;
- while (stu != NULL)
- {
- printf("name: %s \n", stu->name);
- printf("score:%d \n", stu->score);
- stu = stu->next;
- }
- }
- void search_stu(struct Student** head, char name[])
- {
- struct Student* stu, * temp;
- stu = *head;
- int sign = 0;
- if (stu == NULL)
- {
- printf("there is no student!\n");
- }
- else
- {
- while (stu != NULL & sign != 1)
- {
- if (!strcmp(stu->name, name))
- {
- printfInfo(stu);
- sign = 1;
- break;
- }
- else
- {
- stu = stu->next;
- }
- };
- if (sign == 0)
- {
- printf("not found!\n");
- }
- }
-
- }
- void releaseMemory(struct Student** head)
- {
- struct Student* stu, * temp;
- stu = *head;
- while (stu != NULL)
- {
- temp = stu;
- stu = stu->next;
- free(temp);
- }
- }
- void head_add(struct Student** head)
- {
- struct Student* stu, * temp;
- stu = (struct Student*)(malloc(sizeof(struct Student)));
- if (stu == NULL)
- {
- printf("memory failed");
- exit(1);
- }
- getInput(stu);
- if (*head != NULL) //不是空链表
- {
- temp = *head;
- *head = stu;
- stu->next = temp;
- }
- else
- {
- *head = stu;
- stu->next = NULL;
- }
- }
- int main()
- {
- struct Student* namelist = NULL; ////初始化一个指针,头指针,相当于定义了一个空的单链表
- //struct Student* stu = NULL;
- int num;
- printf("total num of stu:");
- scanf_s("%d", &num);
- printf("\n");
- printf("enter info:\n");
- for (int i = 0; i < num; i++)
- {
- head_add(&namelist);
- }
- printf("finish entering!\n");
- //printf("begining to print\n");
- //printfInfo(&namelist);
- char name[20];
- do
- {
- printf("enter the name you want to search:('#'表示结束)");
- scanf_s("%s",name,20);
- search_stu(&namelist, name);
- } while (name[0] != '#');
- releaseMemory(&namelist);
- return 0;
- }
复制代码
本帖最后由 jackz007 于 2021-1-2 15:27 编辑
- void search_stu(struct Student** head, char name[])
- . . . . . .
- while (stu != NULL & sign != 1) // 错误
- {
- if (!strcmp(stu->name, name))
- {
- printfInfo(stu); // 错误
复制代码
改为
- void search_stu(struct Student** head, char name[])
- . . . . . .
- while (stu != NULL && sign != 1) // 修改
- {
- if (!strcmp(stu->name, name))
- {
- printf("name: %s \n", stu->name) ; // 修改
- printf("score:%d \n", stu->score) ; // 修改
复制代码
此外
- printf("enter the name you want to search:('#'表示结束)");
- fflush(stdin) ; // 添加此句,清除键盘缓冲区中滞留的 '\n' 字符,否则,后面的 name[0] != '#' 判断极有可能失效
- scanf("%s",name);
复制代码
|
-
|