简体   繁体   中英

printf alignment with tabs in C

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 (eg 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM