Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of "." in printf

Tags:

c

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.

like image 772
user1369975 Avatar asked Aug 26 '13 13:08

user1369975


People also ask

What is use of %n in printf ()?

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.

What is %f in printf?

The f in printf stands for formatted, its used for printing with formatted output.

What is %2d in printf?

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.


2 Answers

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.

like image 129
TheBlastOne Avatar answered Nov 15 '22 21:11

TheBlastOne


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.

like image 39
Eric Postpischil Avatar answered Nov 15 '22 22:11

Eric Postpischil