![](/img/trans.png)
[英]C++ std::localtime daylight saving time rule (dst) european vs american
[英]Resolving the issue of unsafe function deprecation and misusing time-getting methods like std::ctime() or std::localtime() to get local time in C++
我正在構建一個簡單的小程序來娛樂,消磨時間並學習一些東西。 我只是想讓我的程序顯示當地時間(我住在紐約州布法羅,所以我在東部時間)。 我整理了一個表面上荒謬的庫湯,以確保我的程序了解所有內容:
#include <iostream>
#include <chrono>
#include <ctime>
#include <cstdlib>
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * (x))
#endif
#include <ctime>
#include <iostream>
int main() {
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< "\n";
}
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s" <<
<< std::endl;
}
每次我嘗試某事時,我的努力都伴隨着編譯器,說明如下:
Error C4996 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 15Puzzle C:\Users\owner\source\repos\15Puzzle\main.cpp 10
...當我遵循該建議時,編譯器指出 std 庫沒有推薦的方法。 我真的不想禁用任何警告。
我應該怎么辦?
(答案的想法由 Adrian Mole 和 n. 1.8e9-where's-my-share m. 在對 OP 問題的評論中提供。)
C4996簡直就是微軟設計的絆腳石。 要繞過此“錯誤”,只需將_CRT_SECURE_NO_WARNINGS
標志設置為 true,方法是將以下內容添加到主文件的最頂部:
#define _CRT_SECURE_NO_WARNINGS 1
關於微軟為什么要這樣做的理論似乎不止一種,但事實是使用chrono
庫的傳統函數確實沒有錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.