fmt icon indicating copy to clipboard operation
fmt copied to clipboard

Add more usages for fmt::ostream

Open iwubcode opened this issue 3 years ago • 4 comments

I noticed fmt::output_file() returns a special fmt::ostream. It'd be nice if there was something similar for printing to the screen (cout stream replacement) / building into a string (ostringstream replacement).

Then we could do something like this:

void build_text(fmt::ostream& stream)
{
  stream.print("Hello {}\n", "world");
  stream.print('foobar");
}

// Doesn't matter how you call it!

void to_console()
{
  auto stream = fmt::print();  // no argument overload?  or alternative console_stream();
  build_text(stream);
}

void to_file()
{
  auto stream = fmt::output_file("myfile");
  build_text(stream);
}

void to_string()
{
  auto stream = fmt::string_stream();
  build_text(stream);

  // to text!
  const std::string text = fmt::to_string(stream);
}

at the moment I think we have to fall back to stl streams in order to do this? But I thought those were slow in practice.

Please let me know if there's something I'm missing!

iwubcode avatar Jun 11 '21 20:06 iwubcode

I think this is good idea. It would make code more testable, because you can replace console output with string output and make assertions on that string.

I wonder how hard would be to actually implement it?

WBurzynski avatar Oct 08 '21 19:10 WBurzynski

It'll be also great in embedded platforms, for "printing" to a serial port!

joseangeljimenez avatar Nov 15 '22 12:11 joseangeljimenez

Is any progress?? I want fmtlib more flexible like std::ostream. For example,

void print_something_anywhere(std::ostream &output)
{
  output<<"hello world""<<std::endl;
  // ...
}

Then, the output could be a stdcout or stderr or a file handle.

Can fmtlib implement this?

traversebitree avatar Jun 05 '23 07:06 traversebitree

There is no update on the {fmt}-only solution but you can use std::ostream with {fmt} with the former managing buffering and low-level I/O while the latter doing the formatting.

vitaut avatar Jun 05 '23 22:06 vitaut