C++ 同时写入 std::out 和 std:clog

标签 c++ cout ofstream clog

我想创建一个类似流的类,通过它我可以写入 std::outstd::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/

相关文章:

c++ - 无法找到浮点异常

c++ - QDataStream读取到QVector

C++ 使用 ofstream 写入二进制文件

c++ - 读入一个对象,该对象是另一个对象 C++ 的数据成员

c++ - 如何正确传递 ofstream 对象?

c++ - 在 Debug 中覆盖 memcpy 工作但在 Release 中不工作?

c++ - 不可移动类的对象不可抛出?

C++:打印数组时意外获取十六进制

c++ - Value Printed 根据其后的指令而变化

c++ - 为什么从 write() 调用 __kernel_vsyscall() 永远不会返回?