Friday, January 16, 2009

Text mode: title in a box

When I'm spiking on some experimental code, I often write a little command line application that spews out results to the console. The output can quickly become a sea of lines scrolling away in your terminal window. Drawing a dash and pipe box at the start of each run (or for each section of output) helps me scan through the output.

Here's a quick and easy way to draw and center a title in a dash and pipe box using printf():
void titleBox(char const *title) {
static char const border[] = "+------------------------------------+\n";
static int const borderWidth = sizeof(border) - sizeof("\n"); // minus '\n' and '\0'

int paddingWidth = borderWidth - strlen(title);
int leftPaddingWidth = paddingWidth / 2;
int rightPaddingWidth = paddingWidth - leftPaddingWidth;

printf(border);
printf("%-*c", leftPaddingWidth, '|');
printf(title);
printf("%*c\n", rightPaddingWidth, '|');
printf(border);
}
And the output looks like:
+------------------------------------+
|              My Stuff              |
+------------------------------------+

No comments: