Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more usages for fmt::ostream #2354

Open
iwubcode opened this issue Jun 11, 2021 · 4 comments
Open

Add more usages for fmt::ostream #2354

iwubcode opened this issue Jun 11, 2021 · 4 comments

Comments

@iwubcode
Copy link

iwubcode commented Jun 11, 2021

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!

@WBurzynski
Copy link

WBurzynski commented Oct 8, 2021

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?

@joseangeljimenez
Copy link

joseangeljimenez commented Nov 15, 2022

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

@traversebitree
Copy link

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?

@vitaut
Copy link
Contributor

vitaut commented Jun 5, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants