Left-pad printf with spaces

titaniumdecoy picture titaniumdecoy · Nov 16, 2008 · Viewed 243.7k times · Source

How can I pad a string with spaces on the left when using printf?

For example, I want to print "Hello" with 40 spaces preceding it.

Also, the string I want to print consists of multiple lines. Do I need to print each line separately?

EDIT: Just to be clear, I want exactly 40 spaces printed before every line.

Answer

Bill the Lizard picture Bill the Lizard · Nov 16, 2008

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.