如何在不使用数组的情况下将 chrono::time_point 转换为字符串
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;
}
相关文章:
- 从持续时间构造std::chrono::system_clock::time_point
- 如何在c++迭代器类型中包装std::chrono
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 使用 memcpy() 复制到 std::chrono::milliseconds 会给出错误 -Werror=clas
- std::multimap<std::chrono::milliseconds, T>::rbegin 在 MSVS-13 中指向 end()?
- 如何在C++中将 chrono::秒转换为 HH:MM:SS 格式的字符串?
- C++ Chrono 确定一天是否是周末?
- std::adjacent_difference with std::chrono time_point
- 为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?
- VSCode 说 std::chrono 是模棱两可的,如果运算符<<重载
- 是否确保 2 个连续的 std::chrono::steady_clock::now() 不相等?
- std::chrono::d uration 可以按秒初始化,但不能按毫秒初始化?
- chrono::month 和 chrono::month 有什么区别
- 比较两个 std::chrono::time_point 实例时出错
- 来自 std::chrono 的编译器警告,但未被使用
- 解析某些行的文本和输出"time of appearance"
- 从编译时已知的日历日期创建"std::chrono::time_point"
- std::chrono::time_point from std::string
- 使用 std::chrono::steady_clock 对线程/异步中的代码进行基准测试