如何从输出流创建 std::string? [英] How to create std::string from output stream?
问题描述
请原谅这个简单的问题,但我已经研究了几个小时,但没有成功.我正在尝试实现一个功能:
Forgive the simple question, but I've been at this for hours, with no success. Im trying to implement a function:
std::string make_date_string()
我正在使用 Howard Hinnant 的日期库,它允许我做这样的事情:
I am using Howard Hinnant's date lib, which allows me to do stuff like this:
cout << floor<days>(system_clock::now());
打印如下内容:
2017-07-09
我想弄清楚如何让输出进入 std::string 以便我可以从我的函数中返回它,但我一无所获.
I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.
推荐答案
我想弄清楚如何让输出进入 std::string 以便我可以从我的函数中返回它,但我一无所获.
I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.
在这种情况下,您可以使用 std::ostringstream
:
In such case you can use a std::ostringstream
:
std::ostringstream oss;
oss << floor<days>(system_clock::now());
std::string time = oss.str();
<小时>
附注:
看起来像你的辅助函数
template<typename Fmt>
floor(std::chrono::timepoint);
被实现为iostream操纵器,它可以与任何<代码>std::ostream 实现.
is implemented as an iostream manipulator, it can be used with any std::ostream
implementation.
这篇关于如何从输出流创建 std::string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!