Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create std::string from output stream?

Tags:

c++

stdstring

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.

like image 330
Bas Smit Avatar asked Jul 09 '17 14:07

Bas Smit


People also ask

How do you write a string to a stream in C++?

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

Which writes text from character to output stream?

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 string stream C++?

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.


2 Answers

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.

like image 148
user0042 Avatar answered Nov 13 '22 13:11

user0042


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

like image 3
Howard Hinnant Avatar answered Nov 13 '22 14:11

Howard Hinnant