Bas Smit
Bas Smit

Reputation: 685

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

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.

Upvotes: 8

Views: 3297

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218710

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".

Upvotes: 3

user0042
user0042

Reputation: 8018

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.

Upvotes: 10

Related Questions