That's how:
printf("%*s\n", 10, "This is C");
The format changed from %10s
to %*s
. The printf()
now would expect among the argument, before the string, an int
with the width to pad the string to (the 10
in the example above; obviously could be a variable too).
To tell the printf()
to pad the output to the left (instead of the default right) use the -
: %-*s
. (The output would change from " This is C"
to "This is C "
.)
To tell the printf()
to take only few first bytes from the string, or if the string is not null-terminated, you can add .*
to the format at the same place as the precision for floating point types. The printf()
would print up to that number of characters, stopping at the first null character. Example:
int width = 10;
int chars = 4;
printf( "%-*.*s", width, chars, "This is C" );
would produce output "This "
.