How to create std :: string from output stream?

Sorry, a simple question, but I was in this for hours, without success. Im trying to implement a function:

std::string make_date_string() 

I am using a version of Howard Hinnant date lib that allows me to do things like this:

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

print something like:

 2017-07-09 

I am trying to figure out how I can get this output to go to std :: string so that I can return it from my function, but Im get nowhere.

+5
source share
2 answers

I am trying to figure out how I can get this output to go to std :: string so that I can return it from my function, but Im get nowhere.

In this case, you can use std::ostringstream :

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

As a note:

What does your helper function look like

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

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

+6
source

The accepted answer is a good answer (which I approved).

Here is an alternative wording 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 std::string with the format "2017-07-09" . This particular formulation is good in that you do not need to explicitly create std::ostringstream , and you can easily change 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" .

+3
source

Source: https://habr.com/ru/post/1269653/


All Articles