第三关 通信录

用到结构体知识

任务描述

本关任务:通信录包含

  • “姓名”(最多20个字符)、
  • “生日”(包括“年”、“月”、“日”)、
  • “电话号码”、
  • “家庭地址”(最多50个字符)。

定义一个嵌套的结构类型,输入n(n<10)个学生信息,再按照他们的年龄从小到大的顺序输出。

编程要求

根据提示,在右侧编辑器补充代码,用户先输入正整数n表示学生人数,然后输入这些学生的信息,再按照他们的年龄从小到大的顺序输出。

测试说明

平台会对你编写的代码进行测试:

测试输入:

2 Wangwu 1990 12 11 13901232222 No. 800 Dongchuan Road

Zhangsan 1993 1 23 18912337789 No.238 Huasan Road

预期输出:

Zhangsan 1993 1 23 18912337789 No.238 Huasan Road

Wangwu 1990 12 11 13901232222 No. 800 Dongchuan Road

#include <iostream>
#include <cstring>

using namespace std;

struct birthday{
        int year;
        int month;
        int day;
    };
struct addressBook {
    string name;
    birthday j;
    string phone;
    string address;
};

void ageSort(addressBook a[], int n){
    // 选择排序
    for (int i=0; i<n-1; i++) {
        for (int k=i+1; k<n; k++) {
             if (a[i].j.year > a[k].j.year) continue;
             else if (a[i].j.year == a[k].j.year){
                 if (a[i].j.month > a[k].j.month) continue;
                 else if (a[i].j.month == a[k].j.month) {
                     if (a[i].j.day > a[k].j.day) continue;
                 }
             }
            //另一种写法
            //if (a[i].j.year > a[k].j.year || (a[i].j.year == a[k].j.year && a[i].j.month > a[k].j.month) || (a[i].j.year == a[k].j.year && a[i].j.month == a[k].j.month && a[i].j.day > a[k].j.day)) continue;
            addressBook t;
            t = a[i];
            a[i] = a[k];
            a[k] = t;
        }
    }
}

int main()
{
    int n;
    addressBook a[10];
    cin >> n;
    for (int i=0; i<n; i++) {
        cin >> a[i].name >> a[i].j.year >> a[i].j.month >> a[i].j.day >> a[i].phone;
        getline(cin, a[i].address);
    }
    ageSort(a, n);
    for (int i=0; i<n; i++) {
        cout << a[i].name << ' ' << a[i].j.year << ' ' << a[i].j.month << ' ' << a[i].j.day << ' ' << a[i].phone << a[i].address << endl;
    }
    return 0;
}

知识点 

1. 含空格的输入输出

方法一:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    string s;
    getline(cin, s);
    cout << s;
    return 0;
}

输入:Hello 123*world!

输出:Hello 123*world! 

 方法二:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char c[21];
    int i=0;
    int ch;
    while ((ch=cin.get()) != EOF) {
        c[i] = ch; //注意这里ch不能写成cin.get(),因为ch已经由cin.get()获得了
        i++;
    }
    i = 0;
    cout << endl;
    while (c[i] != '\0') { //也可以写成c[i] != EOF
        cout << c[i];
        i++;
    }
    return 0;
}

字符'\0'就是ASCII码0, 一般用来表示字符串结尾

codeblocks运行结果,上一行为输入,下一行为输出 

 

 2. 选择排序 

 【算法】排序算法之选择排序 - 知乎 (zhihu.com)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值