Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading