In c++, Is it possible to write to some kind of buffer with printf (or similar) and then later in the program either write the buffer to the screen or discard it depending on the outcome.
I want to do this because I have a recursive function and only want the see the things printed throughout the recursion if the result is of interest.
Certainly. You can leverage the power of
vsnprintffor that purpose. I’d suggest some sort of class wrapping anstd::stringorstd::vector<char>(essentially the same in C++11):Now you can say:
If you’re very concerned about performance, you can try and preallocate some space for the print operation and maintain a separate “end” position, in the hope that you’ll never have to run the
vnsprintfcall more than once.