Sorted List Presentation, Part VI

With almost all the former-constants converted to variables, only one puzzle remains: Padding each string’s output so that the columns line up. (Yes, this is the final part of this series!)

From last week’s Lesson, the preferred output width for each string is calculated based on the widest string in the array:

/* set string width for printf() format */
    width = widest(fruit,items);
    if( width % 2 )
        width += 3;     /* assert even width */
    else
        width += 2;     /* at least two spaces padding */

The widest string in the fruit array must be padded with spaces to the right. Otherwise, the output columns look funky. With the widest string value stored in variable width, two or three spaces are added as padding, depending on whether width is odd or even.

The width value is used to display all strings in neat columns. For example, when width is 14 and the string is "apple", you must output the following to get the string to line up in a column with the next row’s text:

"apple         "

Above, that’s “apple” plus nine spaces. I can think of a number of ways to accomplish this task.

One way to set consistent column width is to count characters: Display the string one character at a time, then count up to width while outputting space characters. That’s not the method I used, however. Instead, I looked at a printf() example from an earlier Lesson:

printf("%-12s",fruit[ROWS*c+r]);

The %-12s placeholder outputs a string, left-justified, within a 12-character space. The value 12 is what needs to change at runtime, based on the value of the width variable. To get width into a printf() format string, I used the sprintf() function:

sprintf(format,"%%-%02ds",width);

Variable format is a 6-byte char buffer. The %%-%02ds monster creates a formatting string: % signs must be doubled, and the %02d is replaced by the value of variable width. So if width equals 14, the output sprintf() sends to the format buffer is %-14s, which left-justifies a string in a 14-character space. When variable width holds another value, the format string adjusts accordingly, which helps corral output into the proper-sized columns.

Whew!

All the pieces are together and most everything required to output the fruit array in neat, sorted columns is a variable. It’s a massive puzzle, which I hope that you appreciate why I didn’t set this task as an Exercise; it takes me six Lessons to explain it!

Click here to view the final code, which contains all the bits and pieces described over the past few Lessons.

Now The Boss can add or remove fruit from the array and the only code modification you need to make is to the array itself. The rest of the code accommodates any changes. Try it on your own: Add or remove array elements, make up a long name for some fruit, or shorten all the names to only a few characters. See how the changes are accommodated, thanks to the code’s built-in flexibility.

Leave a Reply