I have the following print in my code
printf("%-*s %s", 20, "string1", "string2");
printf("%-*s %s", 20, "\tstring3", "string4");
I expects it to print the following:
string1 string2
string3 string4
but on some OSs (e.g Ubuntu 16) I get the following
string1 string2
string3 string4
I search everywhere and couldn't find a way around this, I thought %-*s
should have solved my alignment issue but it didn't
CodePudding user response:
TAB is still 1 character. It is printed as 1 character. Then it's up to the terminal to do whatever it wants with it.
This means, printf("%-20s", "\tstring3");
is going to print 1 TAB character, 7 normal characters, and then 12 spaces to arrive at 20.
You need to re-think what you want to do. One way would be to create a function which takes in the string with TABs in it, and returns a string where those have been expanded to spaces. If TAB is always at the start of the string, then you could just replace TABs with 8 (or however many you need) spaces. If you need actual TAB stops, you need a bit more logic to expand them to right amount of spaces.