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.
To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset . The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
What Is the StringStream Class? The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With