Creature

I am trying to create a C ++ ostream for educational reasons. My test will create an ostream that will act like a stream, except that instead of writing to a file, it will write to a container with a detex or vector.

+4
source share
4 answers

As for education, as you say, I will show you how I will do such a thing. Otherwise, stringstream is really the way to go.

It looks like you want to create a streambuf implementation that is then written to the / deque vector. Something like this (copying from another answer from me that targets the / dev / null stream ):

 template<typename Ch, typename Traits = std::char_traits<Ch>, typename Sequence = std::vector<Ch> > struct basic_seqbuf : std::basic_streambuf<Ch, Traits> { typedef std::basic_streambuf<Ch, Traits> base_type; typedef typename base_type::int_type int_type; typedef typename base_type::traits_type traits_type; virtual int_type overflow(int_type ch) { if(traits_type::eq_int_type(ch, traits_type::eof())) return traits_type::eof(); c.push_back(traits_type::to_char_type(ch)); return ch; } Sequence const& get_sequence() const { return c; } protected: Sequence c; }; // convenient typedefs typedef basic_seqbuf<char> seqbuf; typedef basic_seqbuf<wchar_t> wseqbuf; 

You can use it as follows:

 seqbuf s; std::ostream os(&s); os << "hello, i'm " << 22 << " years old" << std::endl; std::vector<char> v = s.get_sequence(); 

If you want to have a deck as a sequence, you can do this:

 typedef basic_seqbuf< char, char_traits<char>, std::deque<char> > dseq_buf; 

Or something like that ... Well, I have not tested it. But perhaps this is also good, so if there are more errors in it, you can try to fix them.

+10
source

Use std :: stringstream

 #include <iostream> #include <sstream> int main() { std::stringstream s; s << "Plop" << 5; std::cout << s.str(); } 
+4
source

I just want to note that for this you do not need to write a class similar to the body. You can use the adapter to achieve your goal.

For example, this code reads from istream and inserts each element into a vector:

 vector<string> V; copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(V)); 
+2
source

Without additional information about what you want to do, it is difficult to be too specific, but you do not want to create a new ostream. What you want to do is create a new streambuf type and use the existing ostream.

The simplest task is to inherit from std :: basic_filebuf <> and overload the sync () and overflow () methods to add elements to your data structures.

+1
source

All Articles