-2

So I want to align my outputs like so:

John Smith         Age: 34  Gender: M
Micheal Smith      Age:  9  Gender: F

and so on

I have an array that contains the information for this and I loop through it and print the information:

for (int i = 0; i < ARRAY_LENGTH; i++) {

      printf ("%s       Age: %d  Gender: \n", person[i].name, person[i].age, person[i].gender);
}

I am stuck on how to make it align so all the spaces are even.

Thanks

Ahmed
  • 292
  • 1
  • 7
  • 15

3 Answers3

3

If you look at the manual for printf(), and note that you can do things like %-18s and %2d - putting a field width and alignment in the format group.

So I'd do something like

printf("%-20s Age:%3d Gender: %1s",
       person[i].name, person[i].age, person[i].gender);

which should align nicely for you.

Kevin Kenny
  • 156
  • 5
  • Curious to use `":%3d"` with no space and then `": %1s"` with space. I'd expect `"Age:%3d Gender:%2s"` or `"Age: %2d Gender: %1s"`. IAC, 3-digit ages make sense. – chux - Reinstate Monica Nov 08 '17 at 02:01
  • @chux: I was going by the example that the original poster gave, keeping the data in the same columns. I figured that overflowing a 3-digit age into the next column to the left was the "least worst" thing to do. – Kevin Kenny Nov 08 '17 at 02:04
  • I'm not convinced the `%1s` gives you any benefit that `%s` doesn't. If you used `%.1s` then you'd limit the output to at most 1 character, but 'at least one' character only gives you a space if the gender is an empty string (so `person[i].gender[0] == '\0'`), so maybe there is a marginal benefit. – Jonathan Leffler Nov 08 '17 at 03:59
  • @JonathanLeffler You're right, it helps only with zero-length 'gender' (which is easy to imagine if there's a database behind this printout, and some people are of indeterminate or 'other' gender). It also serves to document the expected field width. And when I'm producing tabular output, I'm just in the habit of specifying width on ALL fields. – Kevin Kenny Nov 09 '17 at 05:15
2

If you add a width formating to the %, that should get you there. So you can use somethinglike %10s and %5d. Depending on the number spaces you want. Also, you would want to use some sort of monospaced font.

eDog
  • 173
  • 1
  • 5
1

printf allows you to specify padding in the format specifier, you can provide the number of left padding as a number x such that your specifier looks like %xs, or right padding with -x, such that the specifier looks like %-xs.

In your case, you can do something like:

  printf ("%-20s Age: %5d Gender: %s\n", person[i].name, person[i].age, person[i].gender);
TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65