【问题标题】:chrono type to string c++20chrono类型到字符串c ++ 20
【发布时间】:2021-11-08 02:53:26
【问题描述】:

我正在尝试将时间格式化为 hh::mm::ss,然后将其放入宽字符串流中。代码如下。


        std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

        std::chrono::steady_clock::duration time_elapsed = end - start;

        std::chrono::hh_mm_ss formatted {std::chrono::duration_cast<std::chrono::milliseconds> (time_elapsed)};

start 在类的构造函数中。使用 &lt;&lt; 流运算符不起作用,我看不到任何方法可以将此类型转换为字符串。
我的问题是如何将formatted 转换为字符串(c 样式、wstring 或普通字符串)?

【问题讨论】:

  • 你用的是什么编译器?
  • msvc,对比 2019 年
  • 编译器错误说明了什么?
  • 哎呀我想我应该澄清一下,没有错误,我只是需要一种转换为字符串的方法
  • 这能回答你的问题吗? Convert chrono::duration to string or C string

标签: c++ c++20 chrono


【解决方案1】:

以下内容在MSVC 中对我有用。 截至 2021 年 8 月 12 日,我必须将 /std:c++latest 开关与 Visual Studio 版本 16.11.2 一起使用,才能使此解决方案起作用。

const auto start{ std::chrono::steady_clock::now( ) };
std::this_thread::sleep_for( std::chrono::milliseconds{ 1000 } );
const auto end{ std::chrono::steady_clock::now( ) };

const auto elapsed{ end - start };

std::chrono::hh_mm_ss formatted{ 
    std::chrono::duration_cast<std::chrono::milliseconds>( elapsed ) };

std::cout << formatted << '\n';

// Or
std::stringstream ss{ };
ss << formatted;

std::cout << ss.str( ) << '\n';

【讨论】:

  • 您使用了哪些编译器标志?在这里使用 /std:c++20 对 msvc 19.latest 是不够的:godbolt.org/z/GeTv9do46 它只适用于 /std:c++latest(也许这是 OP 问题的一部分)
  • 是的,我使用的是 c++20,切换到 c++latest 我能够让它工作。这是一个前瞻性的解决方案吗?
  • 取决于确切您使用的 2019 版本。如果您使用的是 16.11.x,那么 c++20 应该 可以工作(我自己还没有尝试过),但如果在下面,您将需要 latest
  • @noah 抱歉回复晚了。是的,我使用的是 latest 和 VS 版本 16.11.2。如果我使用 /std:c++20 开关,则此解决方案不起作用(如您在原始问题中所述)。我用这些信息更新了我的答案。
猜你喜欢
  • 2020-07-28
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2013-08-27
  • 1970-01-01
  • 2010-12-28
  • 2010-11-08
相关资源
最近更新 更多