(2.8C)结构体,老师与学生

问题:

 (1)用指向结构体数组的指针来输入输出

//使用指向结构体数组的指针来进行读入读出 
#include<stdio.h>
struct person{
    int num;
    char name[10];
    char sex;
    char job;
    union {
        int classnum;
        char position[10];
    }category;
}st[300];
int main(){
    int n;
    scanf("%d",&n);
    person* p;
    for(p=st;p<st+n;p++){
        scanf("%d",&(p->num)); 
        scanf("%s",p->name);
        getchar();
		scanf("%c",&(p->sex));
		getchar();
		scanf("%c",&(p->job));
		
		if(st[n].job=='s'){
			scanf("%d",&(p->category.classnum));
		}
		else{
			scanf("%s",p->category.position);
		}
    }
    for(p=st;p<st+n;p++){
    	//printf("%d %s %c %c\n",p->num,p->name,p->sex,p->job);
    	if(st[n].job=='s'){
			printf("%d %s %c %c %d\n",p->num,p->name,p->sex,p->job,p->category.classnum);
		}
		else{
			printf("%d %s %c %c %s\n",p->num,p->name,p->sex,p->job,p->category.position);
		}
    	
	}
    return 0;
}

(2)仅用结构体数组

注:和上面那种写法大差不差,看个人习惯

#include<stdio.h>
struct person{
    int num;
    char name[10];
    char sex;
    char job;
    union {
        int classnum;
        char position[10];
    }category;
}st[300];
int main(){
    int n;
    scanf("%d",&n);
    for(int i;i<n;i++){
        scanf("%d",&(st[i].num)); 
        scanf("%s",st[i].name);
        getchar();//读入%c左右有空格记得getchar()一下,因为%c可以读入空格 
		scanf("%c",&(st[i].sex));
		getchar(); 
		scanf("%c",&(st[i].job));
		
		if(st[n].job=='s'){
			scanf("%d",&(st[i].category.classnum));
		}
		else{
			scanf("%s",st[i].category.position);
		}
    }
    for(int i=0;i<n;i++){
    	if(st[n].job=='s'){
			printf("%d %s %c %c %d\n",st[i].num,st[i].name,st[i].sex,st[i].job,st[i].category.classnum);
		}
		else{
			printf("%d %s %c %c %s\n",st[i].num,st[i].name,st[i].sex,st[i].job,st[i].category.position);
		}
    	
	}
    return 0;
}

样例输入:

2
101 Li f s 501
102 Wang m t prof

样例输出:

101 Li f s 501
102 Wang m t prof
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值