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");
}
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.