2

Possible Duplicate:
what does “%.*s” mean in printf in c

I know this question has for sure been asked elsewhere, but searching "%.*s" yields nothing meaningful on SO. Could someone please explain the following line to me?

printf("%.*s", len, buffer);

Community
  • 1
  • 1
pap42
  • 1,236
  • 1
  • 17
  • 28
  • From a reference on `printf`, *(optional) . followed by integer number or * that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int.* – chris Oct 29 '12 at 15:11
  • *::peaks at pap42's tags::* Ah...try `man 3 printf`. One of the nice things about unix is having documentation for both the c standard library and the OS's APIs accessible at the command line. Question for the student: what does the 3 mean and why is it necessary? – dmckee --- ex-moderator kitten Oct 29 '12 at 15:13
  • I assume you meant to put the `*` in your example code. – Mike Oct 29 '12 at 15:14
  • Indeed it's a duplicate; as I said, I could not find anything meaningful on SO using the search tool. I will vote for the deletion of the question. – pap42 Oct 29 '12 at 15:37

2 Answers2

12

It limits the output to at most len characters. The . starts the 'precision'; the * says 'use an int from the argument list to determine the precision'. Note that the 'string' (buffer) does not even have to be null terminated if it is longer than len.

All this is easily found in the manual page for printf().

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

There's a nice table here showing what all the different format specifiers can do for you. For your example, let's say you have a buffer and a length defined as:

char buf[] = "Hello World";
len = 5;

You can use %.*s to print a portion of the full string:

printf("%.*s", len, buffer);

This outputs Hello the first 5 (1 based) characters in this case. Note this is the same as:

printf("%.5s", buffer);
Mike
  • 47,263
  • 29
  • 113
  • 177