How can I clean up misaligned columns in text?

Presumably you are using printf to output the columns in the first place. You can use extra modifiers in your format string to make sure things get aligned.

  • To print a column of a specific width (right-justified), add the width before the formatting flag, e.g., “%10s” will print a column of width 10. If your string is longer than 10 characters, the column will be longer than you want, so choose a maximum value. If the string is shorter, it will be padded with spaces.
  • To left-justify a column, put a – sign in front, e.g., “%-10s”. I like to left-justify strings and right-justify numbers, personally.
  • If you are printing addresses, you can change the fill characters from spaces to zeroes with a leading zero: “%010x”.

To give a more in depth example:

printf("%-30s %8s %8s\n", "Name", "Address", "Size");
for (i = 0; i < length; ++i) {
    printf("%-30s %08x %8d\n", names[i], addresses[i], sizes[i]);

This would print three columns like this:

Name                            Address     Size
foo                            01234567      346
bar                            9abcdef0     1024
something-with-a-longer-name   0000abcd     2048

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)