|
发表于 2021-5-30 23:06:36
|
显示全部楼层
本楼为最佳答案
本帖最后由 stein 于 2021-6-2 22:46 编辑
健壮性有待完善,比如判断人名是否全英文,电话是否全数字。
但是能够达成样例输出了。- #include<stdio.h>
- #include<string.h>
- struct telBook//定义电话本结构
- {
- char name[15];//多留几位,以免超长
- char num[15];//控制电话号码长度,以及避免0开头的数字会产生问题。
- };
- int main()
- {
- int n; //输入本次录入的用户数量
- scanf_s("%d", &n); //VS要求_s的安全形式,但有的编译器不要。函数可改成scanf();
- struct telBook book[50],temp; //生成对象,不超过50个。
- //录入N个用户信息;
- int i; //计数器
- for (i = 0; i < n; i++)
- {
- scanf_s("%s%s", book[i].name, 15, book[i].num,15);
- book[i].name[10] = '\0';//截片
- book[i].num[10] = '\0';//截片
- }
- //人名排序
- for (i = 0; i < n-1; i++)
- {
- if (strcmp(book[i].name, book[i + 1].name) > 0)
- {
- temp = book[i];
- book[i] = book[i + 1];
- book[i + 1] = temp;
- }
- }
- //格式化输出
- unsigned int j;//因为strlen的返回值是无符号
- for(i = 0; i < n; i++)
- {
- for (j = 0; j < 12-strlen(book[i].name); j++)//求出要输出的#个数
- {
- printf("#");
- }
- printf("%s", book[i].name);//输出人名
- for (j = 0; j < 12-strlen(book[i].num); j++)//求出要输出的#个数
- {
- printf("#");
- }
- printf("%s\n",book[i].num);//输出电话号码
- }
- }
复制代码 |
|