When it comes to programming in C and, sometimes, C++, the printf
function is a jack-of-all-trades. It does a nice job of quickly writing output, but it can also do surprisingly intricate formatting. For debugging, it is a quick way to dump some data. But what if you have data that printf
can’t format? Sure, you can just write a function to pick things apart into things printf
knows about. But if you are using the GNU C library, you can also extend printf
to use custom specifications. It isn’t that hard, and it makes using custom data types easier.
An Example
Suppose you are writing a program that studies coin flips. Even numbers are considered tails, and odd numbers are heads. Of course, you could just print out the number or even mask off the least significant bit and print that. But what fun is that?
Here’s a very simple example of using our new printf
specifier “%H”:
printf("%H %H %H %H\n",1,2,3,4); printf("%1H %1H\n",0,1);
When you have a width specification of 1 (like you do in the second line) the output will be H or T. If you have anything else, the output will be HEADS or TAILS.