我一直在尝试用 C++ 获取当前日期一段时间,但我不知道我做错了什么。我查看了几个站点,我实现的所有解决方案都收到一个错误,指出 \xe2\x80\x9cThis 函数或变量可能不安全。考虑使用 localtime_s 代替。\xe2\x80\x9d 我尝试了此处找到的几种解决方案(包括下面的解决方案),但我无法让其中任何一个工作。我究竟做错了什么?
\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <ctime>\n\nusing namespace std;\n\nint main()\n{\n\n const int SALARY = 18;\n const int COMMISSION = .08;\n const int BONUS = .03;\n\n int monthlySales;\n int appointmentNumber;\n\n time_t t = time(0); // get time now\n struct tm * now = localtime(&t);\n\n string name;\n\n\n//this is where the user adds their name and date\n cout << "Please enter the sales representative\'s name: ";\n cin >> name;\n cout << "Please enter the number of appointments: ";\n cin >> appointmentNumber;\n cout << "Please enter the amount of sales for the month: $";\n cin >> monthlySales;\n\n//clear screen and execute code\n system("cls");\n\n cout << setfill(\' \');\n cout << "Sales Representative:" << name << endl;\n cout << "Pay Date:" << (now->tm_mon + 1) << " " << now->tm_mday << " " << (now->tm_year + 1900) << endl;\n cout << "Work Count:" << appointmentNumber << "Sale Amount" \n << monthlySales << endl;\n\n system("pause");\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n
我是这样做的:
#include "date/tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
std::cout << date::make_zoned(date::current_zone(), system_clock::now()) << '\n';
}
Run Code Online (Sandbox Code Playgroud)
这只是为我输出:
2016-10-18 10:39:10.526768 EDT
Run Code Online (Sandbox Code Playgroud)
我使用这个 C++11/14可移植、免费、开源库。它是线程安全的。它基于<chrono>. 它类型安全且易于使用。如果您需要更多功能,这个库可以满足您的需求。
该库正在向 C++ 标准委员会提议,草案请参见此处。