我正在寻找一种方法来将从istream(cin,在我的情况下)读取的输入分支(tee)输出到日志文件(clog)/ofstream /等),同时仍然使用输入进行处理。将输入(cin)输出到日志文件(或阻塞)
我已阅读关于boost :: tee_device,它与我的要求非常相似。不幸的是,它被实现为一个ostream,从而解决了“管道的另一端”类似的问题。
我试图编写一个istream(adapter)类,它将输入函数转发到一个包装输入流(cin),并且还将读取的内容发送到日志文件。
这适用于直接调用操作符>>(...)的基本类型,但是,我遇到了一些更高级的输入流使用问题,例如,对于操作符>>(std ::字符串)和std :: string getline函数。
有没有更简单的方法来做到这一点(可能通过rdbuf()操作)?
谢谢!
编辑:我可以改变我的代码到处都是这样的:cin >> value; clog < < value; - 但这将是一个重大而丑陋的变化。我还希望有一个简单的方法来关闭注销。因此,我想要一种方法来将此模型化为一个istream“过滤器”,然后简单地将所有对cin的引用替换为这个istream“记录器”。
理想的解决方案:
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
}
等
我试着做什么,你在帖子中写道以上在同一时间,和它一直工作,直到特殊字符达到(如endl),然后班级按预期停止工作。我期待在这里看到答案。 – 2009-06-15 21:23:59
这些帮助:[http://stackoverflow.com/questions/999120/c-hello-world-boost-tee-example-program](http://stackoverflow.com/questions/999120/c-hello-world -boost-tee-example-program) [http://stackoverflow.com/questions/670465/using-boostiostreamsteedevice](http://stackoverflow.com/questions/670465/using-boostiostreamsteedevice) – stefanB 2009-06-16 02:06:27