I am looking for a way to branch (tee) the input read from an istream (cin, in my case) out to a log file (clog/ofstream/etc), while still using the input for processing.
I have read about boost::tee_device, and it is very similar to my requirements. Unfortunately, it is implemented as an ostream, and thus solves a similar problem from "the other side of the pipe".
I attempted to write an istream (adaptor) class which forwards the input functions on to a wrapped input stream (cin), and also sends what was read to the log file.
This works fine for basic types which call operator>>(...) directly, however, I have run into issues with some more advanced usage of the input stream, for example, for operator>>(std::string), and the std::string getline function.
Is there any easier way to do this (possibly via rdbuf() manipulation)?
Thanks!
Edit: I could change my code all over the place to something like: cin >> value; clog << value; -- but that would be a significant and ugly change. I would also prefer to have an easy way to turn logging off. Thus, I would like a way to model this as an istream "filter" and then simply replace all references to cin with this istream "logger".
Ideal Solution:
class log_istream : public std::istream
{
public:
log_istream( std::istream & in , std::ostream & out );
/* ... istream forwarding functions ... */
private:
std::istream & in_;
std::ostream & out_;
};
int main() {
log_istream logger( std::cin , std::ofstream("logfile.out") );
logger >> value; // this implies infile >> value and logfile << value
getline(logger,my_string); // this also implies logfile.writeline(value)
// etc
}
etc.