Boost logo

Boost Users :

Subject: [Boost-users] [iostreams] multichar_output_filter works only the first time
From: Steven Samuel Cole (steven.samuel.cole_at_[hidden])
Date: 2012-02-09 11:43:41


to get started with iostreams, i'm trying to write a multichar output
filter that adds a string to the beginning and the end of whatever comes
through. my code builds with a warning about unused parameter n and
works - but only the first time, the second time, i get no output.

i thought at first sending '\0' would trigger the stream's fail-bit or
so, but out.good() returns true.

any chance someone takes a look at my code and hazards a guess where the
problem might be ?

disclaimer: i was actually born and bred in C++ country long time ago,
but i've been coding in python for a couple of years and got back only
recently, so there's a good chance what i'm doing wrong is something
really simple. guess you can tell from the code, it's been a while. good
to be back though... :-)

#include <iostream>
#include <sstream>

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

using std::cin;
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

     template<typename Sink>
     streamsize write(Sink& sink, const char* s, streamsize n)
         // remove trailing '\0' to prevent line break
         // TODO: there's probably a better way
         string tmp_string = string(s);
         string out_string = tmp_string.substr(0, tmp_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,

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

     cout << "prompt: ";

     string str;
     while (getline(cin, str))
         out << str << endl;
         cout << "prompt: ";

# sample session:

prompt: some string
prepended string - some string - appended string
prompt: another string
prompt: why no output ?

# ssc

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at