《算法笔记》2.8小节——C/C++快速入门->结构体(struct)的使用 问题 B: C语言11.2

《算法笔记》2.8小节——C/C++快速入门->结构体(struct)的使用

问题 B: C语言11.2

题目描述

定义一个结构体student,存储学生的学号、名字、性别和年龄,读入每个学生的所有信息,保存在结构体中,并输出。结构体student的定义如下:
struct student {
    int num;
    char name[20];
    char sex;
    int age;
};
本题要求使用指向结构体数组的指针进行输入和输出。

输入

第一行有一个整数n,表示以下有n个学生的信息将会输入。保证n不大于20。
以后的n行中,每一行包含对应学生的学号、名字、性别和年龄,用空格隔开。保证每一个人名都不包含空格且长度不超过15,性别用M和F两个字符来表示。

输出

有n行,每行输出一个学生的学号、名字、性别和年龄,用空格隔开。
请注意行尾输出换行。

样例输入

3
10101 LiLin M 18
10102 ZhangFun M 19
10104 WangMin F 20

样例输出

10101 LiLin M 18
10102 ZhangFun M 19
10104 WangMin F 20

实现代码:

1,

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

struct student {
    int num;
    char name[20];
    char sex;
    int age;
};
int main()
{   
	int n;
	scanf("%d",&n);
	getchar();
	student Stu[n];
	student *sp=Stu;
	for(int i=0;i<n;i++)
	{
	   scanf("%d %s %c %d",&sp[i].num,sp[i].name,&sp[i].sex,&sp[i].age);
	}
	for(int i=0;i<n;i++)
	{
	   printf("%d %s %c %d\n",sp[i].num,sp[i].name,sp[i].sex,sp[i].age); 
	}
	
	return 0;
}

2,

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

struct student {
    int num;
    char name[20];
    char sex;
    int age;
};
int main()
{   
	int n;
	scanf("%d",&n);
	getchar();
	student Stu[n];
	student *sp=Stu;
	for(int i=0;i<n;i++)
	{
		cin>>(sp+i)->num>>(sp+i)->name>>(sp+i)->sex>>(sp+i)->age;
		
	}
	for(int i=0;i<n;i++)
	{
	    cout<<(sp+i)->num<<" "<<(sp+i)->name<<" "<<(sp+i)->sex<<" "<<(sp+i)->age<<endl;
	}
	
	return 0;
}

结果如下:

3
10101 LiLin M 18
10102 ZhangFun M 19
10104 WangMin F 20
10101 LiLin M 18
10102 ZhangFun M 19
10104 WangMin F 20

注意:

当使用scanf进行结构体数组输入时,应当注意字符串类型不需要加取符&。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值