【问题标题】:Is there a way to store date and time in a struct? C++有没有办法在结构中存储日期和时间? C++
【发布时间】:2015-08-17 23:21:36
【问题描述】:

我需要将当前日期和时间存储在字符串中以将其存储在结构中。我什至不知道这是否可能,但我需要这样做。我将尝试进一步解释:

我有这个结构:

struct Apartment{
int number;
string owner;
string condition;
}ap

这段代码添加了相同结构的新对象:

cout << "Enter the apartment number: " << endl;
cin >> ap.number;
cout << "Enter the name of the owner: " << endl;
cin >> ap.owner;
cout << "Enter the condition: " << endl;
cin >> ap.condition;

我需要一个日期和时间的变量。我需要它来保存创建对象的时间和日期。我不知道我是否可以用字符串或其他任何东西来做到这一点。我也需要它是可打印的。如果您能帮助我,我将不胜感激。

【问题讨论】:

    标签: c++ date time struct


    【解决方案1】:

    您可以像这样使用std::time_tstd::time()std::ctime()

    #include <ctime>
    #include <string>
    #include <iostream>
    
    struct Apartment
    {
        int number;
        std::string owner;
        std::string condition;
        std::time_t when;
    };
    
    int main()
    {
        Apartment ap;
    
        std::cout << "Enter the apartment number: " << std::endl;
        std::cin >> ap.number;
    
        std::cout << "Enter the name of the owner: " << std::endl;
        std::cin >> ap.owner;
    
        std::cout << "Enter the condition: " << std::endl;
        std::cin >> ap.condition;
    
        ap.when = std::time(0);// set the time to now
    
        std::cout << "Record created on: " << std::ctime(&ap.when) << std::endl;
    }
    

    【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2021-11-22
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多