Adrian Adrian - 2 months ago 15
C Question

Variable length of columns in C

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

[1] [2] [3]
[4] [5] [6]
[7] [8] [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?

Answer

You could check for the largest number and get its digit. Then prepend 0's to every variable while printing them.

This code gets max in array;

static int max;
for ( int i=0; i<3 /* Or Matrix Rowsize */; ++i ) {
    for ( int j=0; j<3 /* Or Matrix Colsize */; ++j ) {
        if ( max < mat[i][j] ) max = mat[i][j];
    }
}

This code is for finding its digit;

static int digit;
while ( max != 0 ) {
    max /= 10;
    ++digit;
}

Now you can print if using

printf("%%dd", digit, mat[i][j]);

or equivalent C++ style

#include<iomanip>
cout << setw(digit) << mat[i][j];

your output would be:

max = 34313
digit = 5

[00198] [00002] [34313] 
[00004] [00054] [00006] 
[00007] [00888] [00009]