有没有办法在结构中存储日期和时间? C++

Is there a way to store date and time in a struct? C++

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

我有这个结构:

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;

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

您可以这样使用 std::time_t, std::time() and 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;
}