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

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 (e.g Ubuntu 16) I get the following

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

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

>Solution :

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.

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