0

In C, as I understand so far, this would be correct:

printf("%10s\n", "This is C");  

would return:

" This is C!"  

(with the intentional space prior to the string; no quotations).

My question is can you replace the 10 specifying the length of the print using a variable? If so, how?

Dummy00001
  • 16,630
  • 5
  • 41
  • 63

1 Answers1

1

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

Dummy00001
  • 16,630
  • 5
  • 41
  • 63