static_sid
static_sid

Reputation: 23

How to align the numbers properly?

I have tried using %-20s and \t but it wont give me the correct result, I am taking input from a file. I want all the 0's aligned correctly.

Here is my printf statement:

printf("%2d. %-20s%-20s %20d %7d %7d %7d\n", n + 1,
           unit[n].name,
           unit[n].muscles,
           unit[n].weight,
           unit[n].time,
           unit[n].sets,
           unit[n].reps);

This is my output:

I want the 0's of exercise 2 to be aligned properly

Upvotes: 0

Views: 81

Answers (2)

chux
chux

Reputation: 154065

Rather than guess at the needed size, use variable width and let code do the calculation.

int m_width = 1;
for (n=0; n<N; n++) {
  int len = strlen(unit[n].muscles);
  if (len >m_width) {
    m_width = len;
  }
}
...

//                  v-- width
printf("%2d. %-20s%-*s %20d %7d %7d %7d\n", n + 1,
       unit[n].name,
       m_width, unit[n].muscles,
       unit[n].weight,
       unit[n].time,
       unit[n].sets,
       unit[n].reps);

Likewise for other memebrs..

Upvotes: 0

Marco Bonelli
Marco Bonelli

Reputation: 69367

The 20 in the second %-20s in your format string is too low, you have a longer string than that. You must use a bigger number in order for it to be correctly aligned.

Upvotes: 1

Related Questions