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");
}
2
Answers
Instead of using tabs to align columns, use the width field.
%-20s
will left justify the text in a 20 character wide field.%5d
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.
The TAB character means, "move to the next tab stop", where tab stops are usually every 8 characters.
Consider this program:
On my computer (with 8-character tabstops), it prints:
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.