views:

427

answers:

5

I want to define a class MyStream so that:

MyStream myStream;
myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl;

gives output

[blah]123
[blah]56
[blah]78

Basically, I want a "[blah]" inserted at the front, then inserted after every non terminating std::endl ?

The difficulty here is NOT the logic management, but detecting and overloading the handling of std::endl. Is there an elegant way to do this?

Thanks!

EDIT: I don't need advice on logic management. I need to know how to detect/overloading printing of std::endl.

+9  A: 

Your overloaded operators of the MyStream class have to set a previous-printed-token-was-endl flag.

Then, if the next object is printed, the [blah] can be inserted in front of it.

std::endl is a function taking and returning a reference to std::ostream. To detect it was shifted into your stream, you have to overload the operator<< between your type and such a function:

MyStream& operator<<( std::ostream&(*f)(std::ostream&) )
{
    std::cout << f;

    if( f == std::endl )
    {
        _lastTokenWasEndl = true;
    }

    return *this;
}
Timbo
Unfortunately, this does not detect just std::endl - it detects any manipulator that has no parameters. But I guess in the <<() operator you could compare f with std::endl, and do special processing if they are the same thing.
anon
In the middle of editing the post I wasn't sure if the comparison to endl would work, but I tested it and it does :-)
Timbo
This won't work for the same reason as you can never derive from `ostream`: formatting inserters are defined to return an `ostream
Potatoswatter
The code as it stands turns off all the other manipulators - you need to call them in the "else" logic: f( *this );
anon
This should work, except that GCC complains "assuming cast to type 'std::basic_ostream<char, std::char_traits<char> > they are passed to `std::cout` and applied there.
Jon Purdy
A: 

You can't change std::endl - as it's name suggests it is a part of the C++ Standard Library and its behaviour is fixed. You need to change the behaviour of the stream itself, when it receives an end of line . Personally, I would not have thought this worth the effort, but if you want to venture into this area I strongly recommend reading the book Standard C++ IOStreams & Locales.

anon
Good book. But not one I recommend of beginners. But if you want to learn how to manipulate the stream classes it is a must read.
Martin York
@Martin I wouldn't recommend it to beginners either, but then writing specialised streams is not a task for beginners.
anon
Agreed: <-----15 Char ------> :-)
Martin York
+1  A: 

Agreed with Neil on principle.

You want to change the behavior of the buffer, because that is the only way to extend iostreams. endl does this:

flush(__os.put(__os.widen('\n')));

widen returns a single character, so you can't put your string in there. put calls putc which is not a virtual function and only occasionally hooks to overflow. You can intercept at flush, which calls the buffer's sync. You would need to intercept and change all newline characters as they are overflowed or manually synced and convert them to your string.

Designing an override buffer class is troublesome because basic_streambuf expects direct access to its buffer memory. This prevents you from easily passing I/O requests to a preexisting basic_streambuf. You need to go out on a limb and suppose you know the stream buffer class, and derive from it. (cin and cout are not guaranteed to use basic_filebuf, far as I can tell.) Then, just add virtual overflow and sync. (See §27.5.2.4.5/3 and 27.5.2.4.2/7.) Performing the substitution may require additional space so be careful to allocate that ahead of time.

- OR -

Just declare a new endl in your own namespace, or better, a manipulator which isn't called endl at all!

Potatoswatter
You are over complicating things. Use the std::stringbuf class to do the buffering.
Martin York
@Martin: He asked how to change the behavior of `ostream`. I can only assume he wants to work with files. Anyway, even if you use `stringbuf`, you're still in the same situation of deriving, overloading, and substituting: it doesn't simplify anything. Forgetting the whole streams mess and performing search-and-replace on the result of `mystringstream.str()`, on the other hand, would be very reasonable!
Potatoswatter
@Patatoswatter: Please read my solution. I think 30 lines (including comments) is relatively trivial.
Martin York
@Martin: yes, it's simple, but on the scale of complexity it's somewhere between what I thought and "use the std::stringbuf class".
Potatoswatter
+7  A: 

What you need to do is write your own stream buffer:
When the stream buffer is flushed you output you prefix characters and the content of the stream.

The following works because std::endl causes the following.

1) Add '\n' to the stream.
2) Calls flush() on the stream
2a) This calls pubsync() on the stream buffer.
2b) This calls the virtual method sync()
2c) Override this virtual method to do the work you want.

#include <iostream>
#include <sstream>

class MyStream: public std::ostream
{
    // Write a stream buffer that prefixes each line with Plop
    class MyStreamBuf: public std::stringbuf
    {
        std::ostream&   output;
        public:
            MyStreamBuf(std::ostream& str)
                :output(str)
            {}

        // When we sync the stream with the output. 
        // 1) Output Plop then the buffer
        // 2) Reset the buffer
        // 3) flush the actual output stream we are using.
        virtual int sync ( )
        {
            output << "[blah]" << str();
            str("");
            output.flush();
            return 0;
        }
    };

    // My Stream just uses a version of my special buffer
    MyStreamBuf buffer;
    public:
        MyStream(std::ostream& str)
            :std::ostream(&buffer)
            ,buffer(str)
        {
        }
};


int main()
{
    MyStream myStream(std::cout);
    myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl;
}

> ./a.out
[blah]123 
[blah]56 
[blah]78
>
Martin York
-1: You copied my advice without giving credit, instead leaving criticism (huh?), and furthermore only went halfway. You didn't override `overflow`, so your code fails if `putc('\n')` results in overflow before `sync` gets called.
Potatoswatter
Ohhh, overflow never happens in a `stringbuf`. Sorry… it's sunrise here… sleepy.
Potatoswatter
Yeah… if you apply a token edit I'll reverse that vote… tomorrow
Potatoswatter
@potatoswatter: That's a bit egotistical to think I copied you. No copying involved. You came up with a description of possibilities. I came up with a solution. And we did it completely independently. Guss what: I have done this kind of thing before :-)
Martin York
@Martin: I was a bit grouchy and crazy having spent the entire night doing SO unable to sleep… I just shouldn't have been talking to anyone. Really, sorry.
Potatoswatter
A: 

Instead of attempting to modify the behavior of std::endl, you should probably create a filtering streambuf to do the job. James Kanze has an example showing how to insert a timestamp at the beginning of each output line. It should require only minor modification to change that to whatever prefix you want on each line.

Jerry Coffin