如何在不使用数组的情况下将 chrono::time_point 转换为字符串

how to convert chrono::time_point to string without using array?

本文关键字:time chrono point 字符串 转换 情况下 数组      更新时间:2023-10-16

我在 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;
}