-1

I am trying to create a graphical table in C by using a 2D int array. It all works well but the problem is that if the integer's length's are different, the table doesn't look good anymore. Here is an example:

Good

[ 198 ] [  2  ] [34313]
[  4  ] [  54 ] [  6  ]
[  7  ] [ 888 ] [  9  ]

Not good

[198] [2] [34313]
[4] [54] [6]
[7] [888] [9]

What I come up with was to get the length of the biggest int and then use %-Xd for spacing but I don't know how to use a variable at the place of the X. My thought was to replace X by %d, i.e. printf(" [%-%dd]", maxLength, mat[i][j]); but all I get is [%dd].

Does anyone know of a way to solve this problem?

Adrian
  • 908
  • 9
  • 8

1 Answers1

2

There are two main options:

  1. Create the format string at run-time with the correct value for X in the string:

    char format[8];
    snprintf(format, sizeof(format), "%%%dd", width);
    printf(format, matrix[row][col]);
    
  2. Read the printf() documentation and use * in the format string to indicate that the width should be read from a value:

    printf("%*d", width, matrix[row][col]);
    

Both of these right-justify the number in a minimum width. If the value is too big to fit, it will be printed anyway, using extra space as necessary.

If you want zero padding, you can either add a 0 to the format (%05d) or use a precision (%.5d) or use %.*d. You can force signs with +; you can left-justify with -, etc.

Note that when determining the maximum width, negative numbers require an extra space for the minus sign and you need to analyze the minimum as well as the maximum value to make sure you have enough space. If the maximum number is 9 and the minimum is -100,000, then using the maximum number to determine the width won't work well. Clearly, if your values are all non-negative, this is a non-issue.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278