Formatting lines and text in a grid so that they look cohesive in C

I am trying to make my code more beautiful, but I am 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 is the code I have for the print statement:

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

I would like it to look like 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?

+4
source share
1 answer

The trick is to type a colon with the correct number of spaces after it. You can do this by using several functions that it printfprovides:

  • printf returns the number of characters printed
  • printf , . "%-10s" , 10 10.
  • , . printf( "%-*s", 10, "hello" ) "hello", 5

, :

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

Source: https://habr.com/ru/post/1658513/


All Articles