0

Loki Astari provides this custom steam buffer. How can I change the class to automatically flush when reading from cin::cin or when the application exists? For example:

int main ()
{
    MyStream myStream(std::cout);
    myStream << "This does not print.";
}

and

int main()
{
    MyStream myStream(std::cout);
    myStream << "This does not print.";
    std::cin.get();
}

whereas

std::cout << "This does print.";

and

std::cout << "This does print.";
std::cin.get();

If I force it

myStream << "This will now print." << std::flush;

However, I am hoping to replicate the cout behavior of triggering at program exit or std::cin automatically.

This works (thanks to Josuttis's "The C++ Standard Library"):

    MyStream myStream(std::cout);
    std::cin.tie(&myStream);
    myStream << "This will now print.";
    std::cin.get();

because std::cint.tie(&std::cout) is a predefined connection.

Question #1: Can I modify the MyStream class to tie it to the cin stream so that I do not have to issue a std::cin.tie(&myStream) every time I create an instance?

Question #2: How can the MyStream class be modified so that the buffer will be automatically flushed at program exit?

Community
  • 1
  • 1
Macbeth's Enigma
  • 375
  • 3
  • 15
  • 1
    Call `cin.tie(this)` in your stream's constructor. Bear in mind that this will destroy the tie `cin` has with `cout`. For doing stuff at program's exit, use a static object with a destructor. – n. m. could be an AI Jul 08 '13 at 17:34
  • @n.m. Thanks. Put it in the form of an answer and I'll mark it answered. :) Interestingly, cin.get() still flushes cout & MyStream. If I `myStream << "print"; cin.get(); cout << "print with cout"; cin.get()` both flush properly. But if I `myStream << "Print"; cout << "print with cout ";` console shows `print with cout Print`. cout must be destroyed before myStream? – Macbeth's Enigma Jul 08 '13 at 18:03

1 Answers1

1
  1. Constructors are designed to do things at object creation time, so it would be appropriate to establish the tie in the constructor of MyStream: std::cin.tie(this);. This will probably break any tie that exists between cin and cout, and.or between cin abd another instance of your stream class.
  2. For doing things at program exit, C++ has destructors of objects with static storage duration.
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243