C语言编程题 求解

2025-04-09 05:20:12
推荐回答(1个)
回答1:

按照题意,表格使用结构链表实现。其中成员班级或工龄,使用自定义的联合体union(就是题目要求的共用体)。
函数异常不做处理,直接抛出,你需要可以在调用时判断处理异常。

#include

#include

typedef union info4

{

char cName[10];//班级名称

int wAge;//工龄

}IO4;

typedef struct stInfo

{

int id;//编号

char name[10];// 姓名

int pType;//职业类别:0表示学生,1表示教师

IO4 cwInfo;//对应职业类别的班级或工龄

struct stInfo *next;

}STINFO;

int inputInfo(STINFO **stHead,STINFO **stTail);//输入,调用一次输入一条信息,并生成或加入链表,成功返回1,失败返回0

void prfInfos(STINFO *stHead);// 打印链表

int main()

{

STINFO *stHead=NULL,*stTail=NULL;

int n=4;//测试就输入4个,需要自己改

while(n--)

if(!inputInfo(&stHead,&stTail))

{

printf("异常终止!\n");

return 1;

}

prfInfos(stHead);

return 0;

}

void prfInfos(STINFO *stHead)// 打印链表

{

printf("编号   姓 名   职业 班级\\工龄\n");

while(stHead->next)

{

printf("%d %9s %s",stHead->next->id,stHead->next->name,stHead->next->pType?"教师":"学生");

if(stHead->next->pType)

printf("%9d\n",stHead->next->cwInfo.wAge);

else

printf("%9s\n",stHead->next->cwInfo.cName);

stHead=stHead->next;

}

}

int inputInfo(STINFO **stHead,STINFO **stTail)//输入,调用一次输入一条信息,并生成或加入链表,成功返回1,失败返回0

{

static int id=1;

STINFO *head=*stHead,*tail=*stTail,*stNew=NULL;

stNew=(STINFO *)malloc(sizeof(STINFO));

stNew->pType=-1;

stNew->next=NULL;

if(!stNew)//抛出异常

return 0;

stNew->id=id++;

printf("请输入姓名:"),scanf("%9s",stNew->name);

if(getchar()!='\n')//抛出异常

return 0;

while(stNew->pType<0 || stNew->pType>1)

printf("请输入职业编号(0:学生,1:教师):"),scanf("%d",&stNew->pType);

switch(stNew->pType)

{

case 0:printf("请输入学生所在班级名称:");

scanf("%9s",stNew->cwInfo.cName);

if(getchar()!='\n')//抛出异常

return 0;

break;

case 1:printf("请输入教师的工龄:"),scanf("%d",&stNew->cwInfo.wAge);break;

}

if(head==NULL)

head=(STINFO *)malloc(sizeof(STINFO)),head->next=NULL;

if(head->next==NULL)

head->next=stNew;

else

tail->next=stNew;

tail=stNew;

*stHead=head,*stTail=tail;

return 1;

}