【问题标题】:How can I input a set start and end time using Chrono or ctime libaray如何使用 Chrono 或 ctime 库输入设定的开始和结束时间
【发布时间】:2019-11-20 20:48:56
【问题描述】:

我很难理解 c++ 中的时间。我想像这样输入时间值。

time_t  t = time(0);
tm* now = localtime(&t);
cin >> now->tm_wday >> now->tm_mon >> now->tm_year;

我觉得这是一种错误的做法。我的主要目标是尝试创建开始时间和日期以及结束时间和日期,并让对象运行到给定的结束时间和日期。输入时间值让我感到困惑,并希望得到一些帮助,引导我朝着正确的方向前进。

【问题讨论】:

    标签: c++ c++11 visual-c++ chrono


    【解决方案1】:

    std::localtime 返回的std::tm* 不是存储数据的好地方。请注意std::tm 结构中的所有不同偏移量都很好documented

    仅使用年、月和工作日是不够的。例如,每个月有不止一天有星期六。

    你可以这样做:

    #include <chrono>
    #include <ctime>
    #include <iomanip>
    #include <iostream>
    
    int main() {
        std::tm now{}; // declare and initialize your own tm
        std::chrono::system_clock::time_point cc;
    
        std::cout << "enter\nyear month day\n";
    
        std::cin >> now.tm_year >> now.tm_mon >> now.tm_mday;
    
        // compensate for offsets
        now.tm_year -= 1900;
        now.tm_mon -= 1;
    
        // convert to std::time_t
        std::time_t n = std::mktime(&now);
    
        // here you get a chrono time_point from the user input
        cc = std::chrono::system_clock::from_time_t(n);
    
        // convert back to std::time_t
        n = std::chrono::system_clock::to_time_t(cc);
    
        // print the result
        std::cout << std::put_time(std::localtime(&n), "%FT%T") << "\n";
    }
    

    输入/输出示例:

    enter
    year month day
    2019 11 20
    2019-11-20T00:00:00
    

    【讨论】:

    • 非常感谢。现在我知道如何输入时间了。
    • @MarcusWilliams 欢迎您!确保在用户输入值后添加完整性检查。如果您输入无效值,它可能会损坏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多