Home > database >  Printing format with printf
Printing format with printf

Time:01-27

I'm doing the past exam and everything has been going well, I've finished the task, but I have some formatting problems.

What I get:

enter image description here

What I want to achieve:

enter image description here

It bothers me and I would be grateful if someone could come up with a solution.

My code for printing the array:

void printArray(int tab[][MAX], int n, int m) {
    for (int j = 0; j < m; j  )
    {
        printf("]", j);
    }
    printf("\n");
    for (int k = 0; k < 3 * n   4; k  )
    {
        printf("-");
    }
    printf("\n");
    for (int i = 0; i < n; i  )
    {
        printf("- |", i);
        for (int j = 0; j < m; j  )
        {
            printf("=", tab[i][j]);
        }
        printf("\n");
    }
}

CodePudding user response:

The offset is off and printf("]", j); makes the heading numbers too wide.

Fix it by prepending the first line, but instead of printf("- |", i); that you use to prepend each line when printing the values, you can use a blank string, printf("%2s |", "");.

void printArray(int tab[][MAX], int n, int m) {
    printf("%2s |", "");   // this fixes the offset

    for (int j = 0; j < m; j  )
    {
        printf("=", j);  // and use the same width as when printing the values
    }
    
    // ...

CodePudding user response:

Here's my solution, with liberal use of width specifiers on the printf statements.

As you change the constant COL_WIDTH, the table should generally automatically adjust.

#include <stdio.h>

void printArray(int tab[][4], int n, int m)
{
    const int COL_WIDTH = 4;
 
    printf("%*.*s|", COL_WIDTH, COL_WIDTH, "");
    for (int j = 0; j < m; j  )
    {
        printf("%*d", COL_WIDTH, j);
    }

    printf("\n%.*s", COL_WIDTH*(n 1) 1, "----------------------------------------");
    
    for (int i = 0; i < n; i  )
    {
        printf("\n%*d |", COL_WIDTH-1, i);
        for (int j = 0; j < m; j  )
        {
            printf("%*d", COL_WIDTH, tab[i][j]);
        }
    }
}

int main(void) {
    int table[][4] = { { 1, 2, 1, 2}, {2, 2, 3, 2}, {1, 3, 2, 3}, {2, 2, 2, 1} };

    printArray(table, 4, 4);
    
    return 0;
}

Output

    |   0   1   2   3
---------------------
  0 |   1   2   1   2
  1 |   2   2   3   2
  2 |   1   3   2   3
  3 |   2   2   2   1
  • Related