【字符串处理之sscanf函数】读入HH:MM:SS:NN型时间;读入日期

读取时间 HH:MM:SS:NN型

函数

//转为毫秒表示,方便比大小
int get(string time)
{
    int h, m, s, ms;
    //从字符串内读数据
    sscanf(time.c_str(), "%d:%d:%d.%d", &h, &m, &s, &ms);
    return h * 3600000 + m * 60000 + s * 1000 + ms;
}

image

样例1
输入

3
23:41:08.023
1:1:09.211
08:01:22.0

输出

1:1:09.211
08:01:22.0
23:41:08.023

样例2
输入

2
22:41:08.023
22:41:08.23

输出

22:41:08.023
22:41:08.23

样例3
输入

2
01:41:8.9
1:1:09.211

输出

1:1:09.211
01:41:8.9

C++代码

#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>

using namespace std;
using i64 = long long;

const int N = 1e5 + 10;

int get(string time)
{
    int h, m, s, ms;
    sscanf(time.c_str(), "%d:%d:%d.%d", &h, &m, &s, &ms);
    return h * 3600000 + m * 60000 + s * 1000 + ms;
}

bool cmp(string a, string b) { return get(a) < get(b); }

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int n;
    cin >> n;
    vector<string> a;
    for (int i = 0; i < n; i++)
    {
        string s;
        cin >> s;
        a.push_back(s);
    }
    sort(a.begin(), a.end(), cmp);
    for (auto &x : a) cout << x << '\n';
    return 0;
}
posted @   Tshaxz  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
Language: HTML
点击右上角即可分享
微信分享提示