1266 - C语言11.2
定义一个结构体student,存储学生的学号、名字、性别和年龄,读入每个学生的所有信息,保存在结构体中,并输出。结构体student的定义如下:
struct student {
int num;
char name[20];
char sex;
int age;
};
本题要求使用指向结构体数组的指针进行输入和输出。
Input
第一行有一个整数n,表示以下有n个学生的信息将会输入。保证n不大于20。
以后的n行中,每一行包含对应学生的学号、名字、性别和年龄,用空格隔开。保证每一个人名都不包含空格且长度不超过15,性别用M和F两个字符来表示。
Output
有n行,每行输出一个学生的学号、名字、性别和年龄,用空格隔开。
请注意行尾输出换行。
Examples
Input
3 10101 LiLin M 18 10102 ZhangFun M 19 10104 WangMin F 20
Output
10101 LiLin M 18 10102 ZhangFun M 19 10104 WangMin F 20
Solution C
#include <stdio.h> #include <string.h> struct Student { int num; char name[20]; char sex; int age; } st[20]; int main() { int n,i,l; scanf ("%d",&n); for (i=0;i<n;i++) { scanf ("%d %s %c %d",&st[i].num,&st[i].name,&st[i].sex,&st[i].age); l=strlen(st[i].name); st[i].name[l]='\0'; printf ("%d %s %c %d\n",st[i].num,st[i].name,st[i].sex,st[i].age); } return 0; }
Solution C++
#include <stdio.h> struct student { int num; char name[20]; char sex; int age; }stu[20]; int main() { int n; char temp_sex[20]; struct student * p; scanf("%d", &n); for (p = stu;p < stu + n;p++) { scanf("%d %s %s %d", &p->num, &p->name, temp_sex, &p->age); p->sex = temp_sex[0]; } for (p = stu;p < stu + n;p++) printf("%d %s %c %d\n", p->num, p->name, p->sex, p->age); return 0; }