Graham Chapman Graham Chapman - 1 month ago 10
C Question

formatting strings and text in a grid to look cohesive in C

I am trying to make my code print in a little more pretty way but I'm not sure how to fix my problem....

Protein: Donations:0 Requests: 0
Dairy: Donations:0 Requests: 0
Grains: Donations:0 Requests: 0
Vegetables: Donations:0 Requests: 0
Fruits: Donations:0 Requests: 0


Here's the code I have for the print statement:

printf("%s:\tDonations:%d Requests: %d\n", TYPES[i], status[0][i], status[1][i]);


What I would like it to look like is this:

Protein: Donations:0 Requests: 0
Dairy: Donations:0 Requests: 0
Grains: Donations:0 Requests: 0
Vegetables: Donations:0 Requests: 0
Fruits: Donations:0 Requests: 0


Any ideas?

Answer

The trick is to print the colon with the correct number of spaces after it. You can do this by taking advantage of several features that printf provides:

  • printf returns the number of characters that it printed
  • printf can left justify text in a minimum field width, e.g. in the format string "%-10s" the minus sign causes the text to be left justified, and the number 10 specifies a minimum field width of 10.
  • the field width can be passed as a variable, e.g. printf( "%-*s", 10, "hello" ) will print "hello" followed by 5 spaces

Putting it all together, the code would look like this:

int count = printf( "%s", TYPES[i] );
printf( "%-*s", 16-count, ":" );
printf( "Donations:%2d Requests:%2d\n", status[0][i], status[1][i] );