![](/img/trans.png)
[英]Is there a standard way to convert a std::string to std::chrono::time_point without using Boost?
[英]how to convert chrono::time_point to string without using array?
我在 12 天前發布了關於將 std::chrono::time_point 轉換為字符串的問題並解決了問題。 我想對你說聲謝謝。
我使用以下代碼解決了我的問題:
char no[15];
string test;
chrono::system_clock::time_point now = chrono::system_clock::now();
time_t now_c = chrono::system_clock::to_time_t(now);
strftime(no, sizeof(no), "%Y%m%d%I%M%S", localtime(&now_c));
test = no;
cout << test <<endl;
但是,我不喜歡這段代碼,因為我不想使用數組。 我想使用這樣的內存分配來解決我的問題;
char* no = new char();
string test;
chrono::system_clock::time_point now = chrono::system_clock::now();
time_t now_c = chrono::system_clock::to_time_t(now);
strftime(no, sizeof(no), "%Y%m%d%I%M%S", localtime(&now_c));
test = no;
cout << test <<endl;
delete[]no;
不幸的是,這段代碼不起作用。 我認為有一種方法可以做到這一點,但我不知道如何。
如果有人挑出我的錯誤或給我建議,我將不勝感激。
謝謝,
c00012
如評論中所述,您對原始代碼中固定常量 (15) 的依賴是脆弱的; 您使用常量在堆上分配內存並不會使其不那么脆弱(實際上,您在額外代碼中編寫了一個錯誤)。
如果您要分配內存,請讓標准庫更安全地為您分配:
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
int main()
{
const auto now{std::chrono::system_clock::now()};
const auto now_{std::chrono::system_clock::to_time_t(now)};
// A stream into which to write it.
std::stringstream ss;
ss << std::put_time(std::localtime(&now_), "%Y/%m/%d %I:%M:%S %p");
// Your string should now be obtainable via ss.str()
std::cout << ss.str();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.