I want to make my output verbose/non verbose based on a flag given at runtime. My idea is, to construct a std::ostream dependent of the flag, such as in:
std::ostream out;
if (verbose) {
out = std::cout
else {
// Redirect stdout to null by using boost's null_sink.
boost::iostreams::stream_buffer<boost::iostreams::null_sink> null_out{boost::iostreams::null_sink()};
// Somehow construct a std::ostream from nullout
}
Now I'm stuck with constructing a std::ostream from such a boost streambuffer. How would I do this?
Just reset the rdbuf
:
auto old_buffer = std::cout.rdbuf(nullptr);
Otherwise, just use a stream:
std::ostream nullout(nullptr);
std::ostream& out = verbose? std::cout : nullout;
See it Live On Coliru
#include <iostream>
int main(int argc, char**) {
bool verbose = argc>1;
std::cout << "Running in verbose mode: " << std::boolalpha << verbose << "\n";
std::ostream nullout(nullptr);
std::ostream& out = verbose? std::cout : nullout;
out << "Hello world\n";
}
When run ./test.exe
:
Running in verbose mode: false
When run ./test.exe --verbose
:
Running in verbose mode: true
Hello world
You /can/ of course use Boost IOstreams if you insist:
Note, as per the comments, this is strictly better because the stream will not be in "error" state all the time.
Live On Coliru
#include <iostream>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/stream.hpp>
int main(int argc, char**) {
bool verbose = argc>1;
std::cout << "Running in verbose mode: " << std::boolalpha << verbose << "\n";
boost::iostreams::stream<boost::iostreams::null_sink> nullout { boost::iostreams::null_sink{} };
std::ostream& out = verbose? std::cout : nullout;
out << "Hello world\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With