Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print n space characters -(f)printf format

Tags:

c++

c

printf

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.

like image 314
notnull Avatar asked Oct 11 '14 10:10

notnull


People also ask

How do you print a space in printf?

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".

What is %f in printf?

The f in printf stands for formatted, its used for printing with formatted output. Follow this answer to receive notifications.

What does %n in printf do?

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.

What is %d %s %F in C?

%d is print as an int %s is print as a string %f is print as floating point.


1 Answers

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.

like image 154
user3121023 Avatar answered Sep 30 '22 20:09

user3121023