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'?

Lightness Races in Orbit
387k77 gold badges670 silver badges1.1k bronze badges
asked Jun 13, 2011 at 13:44
2
  • 2
    << std::endl does, precisely, << '\n' << std::flush;. Commented Jun 13, 2011 at 13:53
  • 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. Commented Jun 13, 2011 at 16:22

1 Answer 1

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.

answered Jun 13, 2011 at 13:48
Sign up to request clarification or add additional context in comments.

1 Comment

I found that out yesterday myself and overloaded overflow as you say, and now everything works.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.