我需要将当前日期和时间存储在字符串上,以将其存储在结构中。我什至不知道这是否可能,但我需要这样做。我将尝试进一步解释它:
我有这个结构:
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()和 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;
}
关于c++ - 有没有办法在结构中存储日期和时间? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061252/