C++ C++;将格式化数据打印到std::cout或文件(缓冲)

C++ C++;将格式化数据打印到std::cout或文件(缓冲),c++,file,logging,C++,File,Logging,我用了一点。这是他的代码的一部分: class Output2FILE { public: static FILE*& Stream() { static FILE* pStream = stderr; return pStream; } }; 这非常好,因为它只需登录到stderr而无需任何操作,但其功能可以在以后设置为任何内容,包括stdout和一个文件。但是,我认为这种方法不能用于格式化数据,因为需要使用fprintf 因此,我试图想出一些类似的方法,默认

我用了一点。这是他的代码的一部分:

class Output2FILE
{
public:
  static FILE*& Stream() {
    static FILE* pStream = stderr;
    return pStream;
  }
};
这非常好,因为它只需登录到stderr而无需任何操作,但其功能可以在以后设置为任何内容,包括stdout和一个文件。但是,我认为这种方法不能用于格式化数据,因为需要使用fprintf


因此,我试图想出一些类似的方法,默认情况下可以使用stdout,并且可以切换到文件,但是使用“我不太确定我是否正确理解了您要查找的内容。但似乎这个方法可以帮助您:

#include <sstream>

#define SSTR( x ) ( dynamic_cast< std::ostringstream & >( \
            ( std::ostringstream() << std::dec << x ) ).str()
#包括
#定义SSTR(x)(动态_cast)\

(std::ostringstream()您可以使用指向
std::ostream
的指针,就像
文件*
版本一样

std::ostream* os = &std::cerr;
if (log_to_file) {
  os = new std::ofstream("my.log");
}

*os << "Hello Log!" << std::endl;

if (log_to_file) { // or less 'safe' os != &std::cerr ...
    // close file here
}
std::ostream*os=&std::cerr;
如果(记录到文件){
os=流的新标准::(“my.log”);
}
*答案很简单,真的吗

std::ostream& myOutput(std::cout);

谢谢,AFAIK流是不可复制的。这真的是一个简单的答案。
std::ostream&myOutput(std::cout)
确实如此。甚至是一个引用,它可以在输出行上保存取消引用。我本来打算建议这样做,但对于指针,您可以在运行时选择重新定位-例如,如果创建日志文件失败。True。我实际上刚刚在尝试使用全局引用时遇到问题。看起来指针确实更有意义.
std::ostream* os = &std::cerr;
if (log_to_file) {
  os = new std::ofstream("my.log");
}

*os << "Hello Log!" << std::endl;

if (log_to_file) { // or less 'safe' os != &std::cerr ...
    // close file here
}
std::ostream& myOutput(std::cout);