Differences between std::endl and '\n' for streambuffer implementations
Asked Answered
B

1

10

I'm currently trying to implement a subclass of stringbuf to allow the buffer to tokenize for specific chars ('\n' in my case) and undertake an action if this char occurs (dump the message to a logger and clear buffer afterwards in my case). To achieve this goal, I overrode sputc (to implement watching out for the '\n') and xsputn (to use sputc indeed, as the GCC implementation doesn't seem to do this by default). For debugging purposes, I let sputc write out each character that is passed to it to stdout.

Now this is my question: If I use something like

mystream << "Some text" << std::endl;

sputc receives each character except of the '\n' which should be inducted by std::endl, so the action that is expected is not done because the '\n' isn't passed on. If I use something like

mystream << "Some text" << '\n';

or even

mystream << "Some text" << "\n" << std::flush;

everything works as expected and my sputc implementation gets the '\n' char.

So my question is: Shouldn't both code lines do exactly the same concerning the stringbuf behind, and if not, which other methods do I have to override to get the '\n'?

Bombard answered 13/6, 2011 at 13:44 Comment(2)
<< std::endl does, precisely, << '\n' << std::flush;.Imply
There are easier ways to do what you are trying to do. Maybe if you ask a question about the real problem you can get advice about the best way to solve it.Fortunia
D
6

You can't override sputc because sputc is not virtual. You need to overload overflow and sync and examine the whole pending sequence for occurrences of \n.

You shouldn't really need to overload xsputn unless you can do something optimal because you know something special about the device that backs your stream type.

Drais answered 13/6, 2011 at 13:48 Comment(1)
I found that out yesterday myself and overloaded overflow as you say, and now everything works.Bombard

© 2022 - 2024 — McMap. All rights reserved.