[boost] [iostreams] output_filter works only once

1 view
Skip to first unread message

Steven Samuel Cole

unread,
Feb 13, 2012, 1:30:31 AM2/13/12
to bo...@lists.boost.org
i am trying to use an boost::iostreams output filter to add a string to
the beginning and the end of whatever i stream out.

my code below works, but only the first time; the second time, the
output seems to get lost somewhere, the write method doesn't even seem
to get called. i thought at first i'm sending something to the stream
that triggers its fail bit, but the stream seems good.

the same problem occurs on mac and linux, with latest boost release
(1.48) and svn trunk, with cout and a file sink as device.

is that a bug ? or am i doing something wrong in my code ?


#include <iostream>
#include <sstream>

#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/operations.hpp>


using std::cout;
using std::endl;
using std::streamsize;
using std::string;
using std::stringstream;


class add_string_output_filter
: public boost::iostreams::multichar_output_filter
{
public:

template<typename Sink>
streamsize write(Sink& sink, const char* s, streamsize n)
{
string out_string = string(s);

// remove trailing '\0' to prevent line break
if (out_string[out_string.size()-1] = '\0')
out_string = out_string.substr(0, out_string.size()-1);

string pre_string("prepended string - ");
string app_string(" - appended string");

stringstream sstrm;
sstrm << pre_string << out_string << app_string << endl;

// TODO: char* to string, back to char* ?!?
return boost::iostreams::write(sink,
sstrm.str().c_str(),
sstrm.str().length());
}
};


int main()
{
boost::iostreams::filtering_ostream out;

out.push(add_string_output_filter());
out.push(cout);

// string #01 is printed,
// string #02 gets lost
out << "string #01" << endl;
out << "string #02" << endl;
}

_______________________________________________
Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost

Olaf van der Spek

unread,
Feb 13, 2012, 4:43:45 AM2/13/12
to bo...@lists.boost.org
On Mon, Feb 13, 2012 at 7:30 AM, Steven Samuel Cole
<steven.sa...@gmail.com> wrote:
> class add_string_output_filter
>  : public boost::iostreams::multichar_output_filter
> {
>    public:
>
>    template<typename Sink>
>    streamsize write(Sink& sink, const char* s, streamsize n)
>    {
>        string out_string = string(s);

Shouldn't that be string out_string(s, n);?

>        // remove trailing '\0' to prevent line break
>        if (out_string[out_string.size()-1] = '\0')
>            out_string = out_string.substr(0, out_string.size()-1);

I'd use out_string.erase(out_string.size() - 1);

I've no experience with iostreams though, can't help you with the real problem.

Olaf

Reply all
Reply to author
Forward
0 new messages