Adrian - 11 months ago 62

C Question

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`

`%-Xd`

`%d`

`printf(" [%-%dd]", maxLength, mat[i][j]);`

Does anyone know of a way to solve this problem?

Answer Source

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]
```