内核很简单,无非是结构体的使用外加排序。直接上代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stdbool.h>
typedef struct user //注意不能直接给结构体里的数据初始化
{
char name[20];
char num[10];
} user;void paixu (user* yonghu )
{
int i,j;
for (i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
//冒泡排序 -升序
int tmp=0;
for(;tmp<20;tmp++)
{
//遍历每个字符
if(yonghu[j].name[tmp]<yonghu[j+1].name[tmp])
{
break;
}
else if(yonghu[j].name[tmp]==yonghu[j+1].name[tmp])
{
continue;
}
else
{
int cnt=0;
user tmp_1=yonghu[j];
yonghu[j]=yonghu[j+1];
yonghu[j+1]=tmp_1;
break ;
//一开始没想到直接用结构体赋值就行,还每个都分开写
// char tmp_1[20]={'\0'};
// char tmp_2[10]={'\0'};
// for(;cnt<20;cnt++)//调转name
// {
// tmp_1[cnt]=yonghu[i].name[cnt];
// yonghu[i].name[cnt] =yonghu[i+1].name[cnt];
// yonghu[i+1].name[cnt]=yonghu[i].name[cnt];
// }
// for(cnt=0;cnt<10;cnt++)
// {
// tmp_2[cnt]=yonghu[i].num[cnt];
// yonghu[i].num[cnt] =yonghu[i+1].num[cnt];
// yonghu[i+1].num[cnt]=yonghu[i].num[cnt];
// }
// break;
}
}
}
}
}
int main()
{
int i;user yonghu[5];
for (i=0;i<5;i++)
{
memset(yonghu[i].name, 0 ,sizeof(yonghu[i].name));
scanf("%s",yonghu[i].name);
memset(yonghu[i].num, 0 ,sizeof(yonghu[i].num));
scanf("%s",yonghu[i].num);
}
paixu(&yonghu[0]);
for(i=0;i<5;i++)
{
printf("%s\n%s\n",yonghu[i].name,yonghu[i].num);
}
return 0;
}
复习一个知识点:struct是一个申明,其本身并没有申请到空间,所以不能直接给struct里的元素赋值(即无法初始化)