I was just reading the classic K&R and encountered the following syntax:
printf("%.*s",max,s);
What is the meaning of "."
here?When I don't apply a "."
here,then whole string is printed,but when we don't apply a "."
,atmost max characters are printed.I will be really thankful if anyone could explain this.
In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.
The f in printf stands for formatted, its used for printing with formatted output.
It specifies the minimum width that the output should be. If the width specified is more than the size of the output itself (the opposite of your case), then the difference between the length of your output and the width specified will be printed as spaces before your output.
It specifies the "Character String Maximum field width"
The precision within a string format specifies the maximum field width:
%2.6s
specifies a minimum width of 2 and a maximum width of 6 characters. If the string is greater than 6 characters, it will be truncated.
In %.*s
, the .*
limits the number of bytes that will be written. If this were written with a numeral included, such as %.34s
, then the numeral would be the limit. When an asterisk is used, the limit is taken from the corresponding argument to printf
.
From C 2011 (N1570) 7.21.6.1 4, describing conversion specifications for fprintf
et al:
An optional precision that gives … the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero.
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