Is there any way to print certain amount of whitespace characters?
I cant use min. width whitespace padding "\"%-5s\""
, because it would result to "str "...
, and I need to output "str" ...
I know I can do it a dumb way:
int len = strlen (str);
printf ("/"%s/"", str);
for (int i = len - 5; i > 0; i--)
printf (" ");
But I'd appreciate more effective workaround.
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".
The f in printf stands for formatted, its used for printing with formatted output. Follow this answer to receive notifications.
In C language, %n is a special format specifier. It cause printf() to load the variable pointed by corresponding argument. The loading is done with a value which is equal to the number of characters printed by printf() before the occurrence of %n.
%d is print as an int %s is print as a string %f is print as floating point.
Try
printf ( "%*c\"%s\"%*c", leading, ' ', str, trailing, ' ');
Where leading and trailing are int.
For trailing only use
printf ( "\"%s\"%*c", str, trailing, ' ');
Similar modification can be made for leading only
EDIT
The width specifier allows the use of an asterisk to provide a variable width.
In this case %*c is telling printf to get the next argument and use it as the width for the character.
It initially reads leading and uses it for the width of the field in which to print the character, a space character. Then a quote is printed, \". The %s format prints the next argument, str. Another quote is printed and then again %*c reads trailing as the width for the field in which to print the next argument, another space character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With