Custom input stream in C++

The proper way to create a new stream in C++ is to derive from std::streambuf and to override the underflow() operation for reading and the overflow() and sync() operations for writing. - SO

Stream buffers represent input or output devices and provide a low level interface for unformatted I/O to that device. Streams, on the other hand, provide a higher level wrapper around the buffer by way of basic unformatted I/O functions and especially via formatted I/O functions (i.e., operator« and operator» overloads). Stream objects may also manage a stream buffer’s lifetime. - SO

caption

yduf/input_logger.hh

#include "input_logger.hh"

int main() {
    // assume an input stream exist (work as well with cin)
    char a[] = "This is the input\nhello\n";
    std::istringstream in(std::string(std::begin(a), std::end(a)));

    // Then tie in stream to log stream, wich will output every input to cerr
    input_logger log( in);

    // use in stream normally
    std::string first, second;
    getline( in, first);            // will log =>This is the input
    in >> second; in.ignore();      // will log =>hello

    // and it works as expected
    std::cerr << "first is '" << first << "'\n";
    std::cerr << "second is '" << second << "'\n";
}
Written on December 27, 2020, Last update on March 25, 2022
c++ file io-stream codingame