【C++字符串处理】读入日期,读入YYYY-MM-DD HH:MI:SS格式的日期,然后输出年月日时分秒

从标准输入读取示例:

std::tm tm = {};
std::cout << "请输入日期时间 (YYYY-MM-DD HH:MM:SS): ";
std::cin >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");

if (std::cin.fail()) {
    std::cerr << "输入格式无效!" << std::endl;
    return 1;
}

12. 日期时间输入输出I

#include <iomanip>
#include <iostream>

using namespace std;

void solve()
{
    struct tm time = {};
    cin >> get_time(&time, "%Y-%m-%d %H:%M:%S");
    
    cout << time.tm_year + 1900 << '\n'
         << time.tm_mon + 1 << '\n'
         << time.tm_mday << '\n'
         << time.tm_hour << '\n'
         << time.tm_min << '\n'
         << time.tm_sec << '\n';
}

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int T = 1;
    while (T--) solve();
    return 0;
}

13. 日期时间输入输出II

注释版

std::get_time在头文件<iomanip>

#include <iomanip>
#include <iostream>

using namespace std;

void solve()
{
    struct tm time = {};
    // 读取输入并解析为tm结构体
    cin >> get_time(&time, "%Y-%m-%d %H:%M:%S");

    cout << time.tm_year + 1900 << '\n';  // 输出年(直接输出四位,无需补零)
    cout << setfill('0');                 // 后续字段统一设置补零格式
    cout << setw(2) << time.tm_mon + 1 << '\n'  // 月
         << setw(2) << time.tm_mday << '\n'     // 日
         << setw(2) << time.tm_hour << '\n'     // 时
         << setw(2) << time.tm_min << '\n'      // 分
         << setw(2) << time.tm_sec << '\n';     // 秒
}

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int T = 1;
    while (T--) solve();
    return 0;
}

image

image

posted @ 2025-03-06 14:23  Tshaxz  阅读(112)  评论(0)    收藏  举报
Language: HTML