Search code examples
crow

how to set column to straight down like this?


I tried to do a numeric puzzle and I want a column to set of like this

\ ----- ----- ----- -----
|  10 |  1  |  6  |  7  |
\ ----- ----- ----- -----
|  4  |  14 |  3  |  9  |
\ ----- ----- ----- -----
|  2  |  11 |  5  |     |
\ ----- ----- ----- -----
|  15 |  8  |  12 |  13 |
\ ----- ----- ----- -----

I tried to do this by using this code

    printf("\\ ----- ----- ----- -----\n");
    printf("|  %2.1d |  %2.1d |  %2.1d |  %2.1d |\n",a[0][0],a[0][1],a[0][2],a[0][3]);
    printf("\\ ----- ----- ----- -----\n");
    printf("|  %2.1d |  %2.1d |  %2.1d |  %2.1d |\n",a[1][0],a[1][1],a[1][2],a[1][3]);
    printf("\\ ----- ----- ----- -----\n");
    printf("|  %2.1d |  %2.1d |  %2.1d |  %2.1d |\n",a[2][0],a[2][1],a[2][2],a[2][3]);
    printf("\\ ----- ----- ----- -----\n");
    printf("|  %2.1d |  %2.1d |  %2.1d |  %2.1d |\n",a[3][0],a[3][1],a[3][2],a[3][3]);
    printf("\\ ----- ----- ----- -----");

It turn out to be like this

\ ----- ----- ----- -----
|   6 |  14 |  13 |  10 |
\ ----- ----- ----- -----
|   3 |   0 |   4 |   9 |
\ ----- ----- ----- -----
|   2 |   5 |  11 |   7 |
\ ----- ----- ----- -----
|   8 |  15 |  12 |   1 |
\ ----- ----- ----- -----

How can I fixed this. It's seems to work only with 10-15.


Solution

  • From documentation on *printf:

    In general:

    . followed by integer number or *, or neither that specifies precision of the conversion.

    And for %d:

    Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are ​0​ the conversion results in no characters.

    The specifier to use is either "%-2.0d" or %2.0d, depending on if you want the number left- or right-justified, respectively.

    #include <stdio.h>
    
    int main(void) {
        printf("Left-justified:\n");
        printf("| %-2.0d |\n", 6);
        printf("| %-2.0d |\n", 11);
        printf("| %-2.0d |\n", 0);
    
        printf("Right-justified:\n");
        printf("| %2.0d |\n", 3);
        printf("| %2.0d |\n", 14);
        printf("| %2.0d |\n", 0);
    }
    

    Output:

    Left-justified:
    | 6  |
    | 11 |
    |    |
    Right-justified:
    |  3 |
    | 14 |
    |    |
    

    A note about the precision specifier:

    If neither a number nor * is used, the precision is taken as zero.

    This means the form of "%-2.d" would also work.