是我这个修改后的代码能够录入多个人员的数据吗? 我尝试了很多次都不行。。。
#include<stdio.h>
#include <stdlib.h>
struct Ym
{
char name[8];
int age;
char one_time[11];
char two_time[11];
struct Ym *next;
};
void getInput(struct Ym *ym)
{
char ch;
printf("请输入姓名:");
scanf("%s",ym->name);
printf("请输入年龄:");
scanf("%d",&ym->age);
while ((ch = getchar()) != '\n' && ch != EOF); // 添加这行以清空输入缓冲区
printf("请问是否接种过疫苗(Y/N):");
if((ch = getchar()) == 'Y')
{
printf("请输入第一针疫苗接种的日期(yyyy-mm-dd):");
scanf("%s",ym->one_time);
}
else
{
ym->one_time[0] = '0';
printf("\n\n");
return ;
}
while ((ch = getchar()) != '\n' && ch != EOF); // 添加这行以清空输入缓冲区
printf("请问是否接种过第二针疫苗(Y/N):");
if((ch = getchar()) == 'Y')
{
printf("请输入第二针疫苗接种的日期(yyyy-mm-dd):");
scanf("%s",ym->two_time);
}
else
ym->two_time[0] = '0';
//while ((ch = getchar()) != '\n' && ch != EOF); // 添加这行以清空输入缓冲区
printf("\n\n");
}
void addYm(struct Ym **library)
{
struct Ym *ym, *temp;
ym = (struct Ym*)malloc(sizeof(struct Ym));
if(ym == NULL)
{
printf("内存分配失败了!\n");
exit(1);
}
getInput(ym);
if(*library != NULL) //可以分开看 * (*library)看成一个整体 这个代表**library指针指向空间的地址
{
temp = *library;
*library = ym;
ym->next = temp;
}
else
{
*library = ym;
ym->next = NULL;
}
}
void printLibrary(struct Ym *library)
{
struct Ym *ym;
// int count = 1;
ym = library;
while(ym != NULL)
{
printf("姓名:%s ",ym->name);
printf("年龄:%d\n",ym->age);
if(ym->one_time[0] != '0')
printf("第一针疫苗接种日期:%s, ",ym->one_time);
else
{
printf("未接种疫苗!");
ym = ym->next;
break;
}
if(ym->one_time[0] != '0' && ym->two_time[0] != '0')
printf("第二针疫苗接种日期:%s\n\n",ym->two_time);
else
{
printf("未接种第二针疫苗!\n\n");
}
ym = ym->next; //指向下一个结构体 就可以跳出循环了
//count++;
}
}
void releaseLibrary(struct Ym *library)
{
struct Ym *temp;
while (library != NULL)
{
temp = library;
library = library->next;
free(temp);
}
}
int main(void)
{
struct Ym *library = NULL;
char ch;
while(1)
{
printf("请问是否需要录入疫苗信息(Y/N):");
do
{
ch = getchar();
}
while(ch != 'Y' && ch != 'N');
if(ch == 'Y')
{
addYm(&library); //如果用library是指向空间的地址 用&library是library指针本身的地址
}
else
{
printf("\n");
break;
}
}
printf("请问是否需要打印疫苗信息(Y/N):");
do
{
ch = getchar();
}
while(ch != 'Y' && ch != 'N');
if(ch == 'Y')
{
printLibrary(library);
}
releaseLibrary(library);
return 0;
}
|