For those of you who have done a lot of output using printf the following will be familiar, but I think that there are a lot of programmers who have done most of their user interface code with a GUI. I have been getting questions about the format string in DEBUGMSG and RETAILMSG lately. I will not try to be the full documentation on format strings, but I thought that I would explain a few things about the format string that can be useful.
You may have seen some of my examples using %s, %8s and %-*s and maybe even wondered what the numbers, asterisks and minus sign do. Of course C programmers learn early that %s causes a parameter to be output as a string. You can control the width of the string field by putting a number between the ‘%’ and the ‘s’, so %8s says output the string with at least 8 characters and fill the left side with spaces if the string contains less than 8 characters. That can be handly if you want to output columns of data. If we change that to %-8s, the minus sign means to fill to the right with spaces. But what if you don’t know the width of the field when you write the code, but instead calculate it at run time or want to use a macro to set the width?  For more dynamic field width, you can use an asterisk which says that there is a parameter that sets the field width.
                RETAILMSG( 1, (TEXT(">%s<\n"), DriverName ));
                RETAILMSG( 1, (TEXT(">%4s<\n"), DriverName ));
                RETAILMSG( 1, (TEXT(">%4.4s<\n"), DriverName ));
                RETAILMSG( 1, (TEXT(">%*s<\n"), MaxStringLength, DriverName ));
                RETAILMSG( 1, (TEXT(">%-*s<\n"), MaxStringLength,DriverName ));>MyDriver<
Gives the following output, note that I put in > and < to show the string output:
>       MyDriver<
>MyDriver       <
Notice that I also threw in an extra one, %4.4s which says the string should be 4 characters long, and no longer. So the output was MyDr instead of the full MyDriver.
These same format modifiers can be used with %d and %x as well.
Copyright © 2008 – Bruce Eitman
All Rights Reserved