Output Formatting with std::copy

I had to do some output formatting in C++ for showing the content of a buffer. Take for instance this buffer:

I wanted the output to be like this:

The simples way to do it is like this:

That for loop achieves the goal. But then, I though, why not using std::copy? Well, the first thing you can come up with is this:

But that can only produce this output:

That happens because we used unsigned char instead of int for the ostream iterator. You can correct that like this:

and get the output like this:

But this is still far from what I want. The best approach to solve the problem is to use a class that encapsulates a character (or any other type that we want to print), provide a printing function for it and overload the operator<< to output instances of this class. This is shown bellow:

We can now transform the copy call to this:

and the output is:

That is much better, but not yet perfect. To achieve the final goal, we can transform the Printer class to keep a count of the printer elements:

The copy call remains the same, and the output is:

Of course, if you use this several times, you have to reset the static index from the Printer class. I’ll leave that to you.

3 Replies to “Output Formatting with std::copy”

  1. I’m not saying the second solution is simpler or even better. I’ve just shown how is it possible to do it.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.