Home > Blockchain >  Why does Ubuntu terminal display tab characters printed in a loop differently?
Why does Ubuntu terminal display tab characters printed in a loop differently?

Time:12-02

I am doing printf("\t%d", i) in a for-loop to print column labels for a table.

Before the loop, I do printf("some string ===>").

An issue I notice is that for example, if I do printf("some string===>" (one character less), the first tab from the loop doesn't display correctly in my Ubuntu 20.04 terminal.

Why is this?

#include <stdio.h>

int main()
{
     printf("some string ===>");
     for (int j = 1; j <= 9;   j) printf("\t%d", j);
     printf("\n");
     
     printf("some string===>");
     for (int j = 1; j <= 9;   j) printf("\t%d", j);
     printf("\n");
}

Output in my Ubuntu 20.04 terminal Output in my Ubuntu 20.04 terminal

CodePudding user response:

The TAB character means, "move to the next tab stop", where tab stops are usually every 8 characters.

Consider this program:

#include <stdio.h>

int main()
{
    int i, j;
    for(i = 0; i < 16; i  ) {
        for(j = 0; j < i; j  ) putchar('*');
        printf("\tx\n");
    }
}

On my computer (with 8-character tabstops), it prints:

        x
*       x
**      x
***     x
****    x
*****   x
******  x
******* x
********        x
*********       x
**********      x
***********     x
************    x
*************   x
**************  x
*************** x

Your string "some string ===>" is 16 characters long, so after you print it, you're at a multiple of 8, so printing a TAB moves you 8 more spaces to the next multiple of 8 (24).

Your string "some string===>" is 15 characters long, so after you print it, you're one shy of a multiple of 8, so printing a TAB moves you 1 more space, to 16.

CodePudding user response:

Instead of using tabs to align columns, use the width field.
%-20s will left justify the text in a 20 character wide field.
] will right justify the text in a 5 character wide field.
If the length of the text is greater than the specified width, the field will be expanded to accommodate the text.

#include <stdio.h>

int main()
{
     printf( "%-20s", "some string ===>");
     for (int j = 1; j <= 9;   j) printf("]", j);
     printf("\n");

     printf( "%-20s", "some string===>");
     for (int j = 1; j <= 9;   j) printf("]", j);
     printf("\n");
}
  • Related