我想创建一个类似流的类,通过它我可以写入 std::out
和 std::clog
。
我有以下代码,但问题是它只写入 std::clog
,而控制台上的输出并不像预期的那样(奇怪的是,它覆盖了自己)。
struct Log : public std::ofstream
{
Log(const std::string filename)
: std::ofstream(filename.c_str())
{
std::clog.rdbuf(this->rdbuf());
}
};
template <typename T>
Log & operator << (Log & stream, const T & x)
{
std::cout << x;
std::clog << x;
return stream;
};
我要的是这个
Log log("logfile.txt");
log << "this should go to the console and the logfile" << 1234 << std::endl;
这可以做到吗?
最佳答案
我找到了一个(或“那个”)解决方案!
我添加了以下代码:
Log & operator << (Log & stream, std::ostream & (*f)(std::ostream&))
{
std::cout << f;
std::clog << f;
return stream;
}
这增加了接受例如std::endl
(或 std::ostream
中的其他函数调用),现在按预期运行。
关于C++ 同时写入 std::out 和 std:clog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26971989/