2020 BIT冬训-C++STL C - A problem of sorting HDU - 5427
Problem Description
There are many people's name and birth in a list.Your task is to print the name from young to old.(There is no pair of two has the same age.)
Input
First line contains a single integer T≤100 which denotes the number of test cases.
For each test case, there is an positive integer n(1≤n≤100)which denotes the
number of people,and next nn lines,each line has a name and a birth's year(1900-2015)
separated by one space.The length of name is positive and not larger than 100.Notice
name only contain letter(s),digit(s) and space(s).
Output
For each case, output nn lines.
Sample Input
2 1 FancyCoder 1996 2 FancyCoder 1996 xyz111 1997
Sample Output
FancyCoder xyz111 FancyCoder
这题的坑点是名字也有空格!这里需要掌握的知识是字符串的截取,以及需要注意在字符串后面添‘\0’
#include<stdio.h> #include<cstring> #include<algorithm> #include<iostream> using namespace std; struct people{ char name[105]; int birth; }p[105]; int cmp(people a,people b){ if(a.birth == b.birth) return strcmp(a.name,b.name)<0; else return a.birth>b.birth; } char data[115]; int t,n; int main(){ scanf("%d",&t); while(t--){ scanf("%d",&n); cin.get(); for(int i=0;i<n;i++){ cin.getline(data,1024); p[i].birth=0; for(int k = strlen(data) - 4; k < strlen(data); k++){ p[i].birth *= 10; p[i].birth += data[k] - '0'; } data[strlen(data)-5]='\0'; strcpy(p[i].name,data); } sort(p,p+n,cmp); for(int i=0;i<n;i++) printf("%s\n",p[i].name); } return 0; }