c0704 学生记录

【问题描述】
从键盘中读入最多不超多50个学生的学生信息(包括空格隔开的姓名、学好、年龄信息,以学好从低到高排序)
【输入形式】
从键盘中读入最多不超多50个学生的学生信息;
第一行为学生 的人数;
后面每一行为空格隔开的学号,姓名,年龄,其中学号和年龄都是整数
【输出形式】
按姓名从低到高输出;
按年龄从低到高输出,(年龄相同时,按照姓名从低到高输出)
右对齐,占位符3、6、3
【输入样例】
4
1 aaa 22
45 bbb 23
54 ddd 20
110 ccc 19
【输出样例】
1 aaa 22
45 bbb 23
110 ccc 19
54 ddd 20

110 ccc 19
54 ddd 20
1 aaa 22
45 bbb 23

  • 自做答案
//2020/4/4
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct Student
{
	int id;
	char name[50];
	int age;
}stu[50];
int N;
bool cmp1(Student a,Student b)
{
	if( strcmp(a.name,b.name) < 0)
		return true;
	else 
		return false;
}

bool cmp2(Student a,Student b)
{
	if(a.age < b.age)
		return true;
	/*
	else if(a.age == b.age)
	{
		if(strcmp(a.name,b.name) < 0)
			return true;
		else 
			return false;
	}
	else 
		return false;
	*/
	else if(a.age == b.age && strcmp(a.name,b.name) < 0)
		return true;
	else 
		return false;
}
void print()
{
	int i;
	for(i = 0;i<N;i++)
	{
		printf("%3d%6s%3d\n",stu[i].id,stu[i].name,stu[i].age);
	}
}
int main()
{
	int i;
	scanf("%d",&N);
	for(i = 0;i<N;i++)
	{
		int id,age;
		char name[50];
		scanf("%d%s%d",&stu[i].id,stu[i].name,&stu[i].age);
	}
	sort(stu,stu+N,cmp1);//数组首地址的运算,stu+i,相当于stu[i]
	print();
	sort(stu,stu+N,cmp2);
	print();
	return 0;
}
/*
OUT:
  1   aaa 22
 45   bbb 23
110   ccc 19
 54   ddd 20

110   ccc 19
 54   ddd 20
  1   aaa 22
 45   bbb 23
 */
发布了117 篇原创文章 · 获赞 71 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34686440/article/details/105317421