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.
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.
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
int space = 40;
printf("%*s", space, "Hello");
This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40).
Same can be used for characters and integers as follows:
printf("%*d", space, 10);
printf("%*c", space, 'x');
This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:
printf("%*d", 10, 10);
printf("%*c", 20, 'x');
printf("%*s", 30, "Hello");
Hope this helps someone like me in future.
If you want exactly 40 spaces before the string then you should just do:
printf(" %s\n", myStr );
If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces):
printf("%40s%s", "", myStr );
If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this:
printf("%40s", myStr);
You can also put "up to" 40 spaces AfTER the string by doing:
printf("%-40s", myStr);