开发者

C++ Print formatted data either to std::cout or to a file (buffered)

开发者 https://www.devze.com 2023-03-15 12:27 出处:网络
I have been using Petru\'s logging framework a bit. This is part of his code: class Output2FILE { public:

I have been using Petru's logging framework a bit. This is part of his code:

class Output2FILE
{
public:
  static FILE*& Stream() {
    static FILE* pStream = stderr;
    return pStream;
  }
};

Which is very nice as it simply logs to stderr without any action, but with the function that can afterwards be set to anything including stdout and a file. However, I t开发者_开发问答hink this approach can't be used for formatted data as one needs to use fprintf.

Hence I am trying to come up with something similar that lets one use stdout by default and that can be switched to a file, but using the "<<" operator for formatted data.

Maybe something along the lines of

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

with the idea of then doing myOutput << "Hello" << 1 << 1.5;. Above line however makes the compiler complain though.

What is the correct way?

Thanks!


You could use a pointer to an std::ostream much like the FILE* version.

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
}


Easy answer, really

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

Thanks


I am not quite sure I understood correctly what you're looking for. But it seems as if this one could help you:

#include <sstream>

#define SSTR( x ) ( dynamic_cast< std::ostringstream & >( \
            ( std::ostringstream() << std::dec << x ) ).str()

Usage:

SSTR( "Hello" << 1 << 1.5 );

Yields std::string (which you can then feed to whatever output function you want).

Elaborate description and explanation: http://dev.rootdirectory.de/trac.fcgi/wiki/SSTR%28%29

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号