How to create std::string from output stream?

谁都会走 提交于 2020-01-03 11:37:06

问题


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()

I am using Howard Hinnant's date lib, which allows me to do stuff like this:

cout << floor<days>(system_clock::now());

printing something like:

2017-07-09

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.


回答1:


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.

In such case you can use a std::ostringstream:

std::ostringstream oss;
oss << floor<days>(system_clock::now());
std::string time = oss.str();

As a side note:

As it looks like your helper function

template<typename Fmt>
floor(std::chrono::timepoint);

is implemented as an iostream manipulator, it can be used with any std::ostream implementation.




回答2:


The accepted answer is a good answer (which I've upvoted).

Here is an alternative formulation using the same library:

#include "date.h"
#include <string>

std::string
make_date_string()
{
    return date::format("%F", std::chrono::system_clock::now());
}

which creates a std::string with the "2017-07-09" format. This particular formulation is nice in that you don't have to explicitly construct a std::ostringstream, and you can easily vary the format to whatever you like, for example:

    return date::format("%m/%d/%Y", std::chrono::system_clock::now());

which now returns "07/09/2017".



来源:https://stackoverflow.com/questions/44997424/how-to-create-stdstring-from-output-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!