I got a code snippet in which there is a
printf("%.*s\n")
what does the %.*s
mean?
%s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char ); the type of the corresponding argument must be char * . %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int .
*” and specifier is “s”. width = * means “The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.”. That means before the string argument to be printed, you need to provide an integer argument that specifies the width.
We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
%2d means: Suppose you are printing n= 18999 with printf("%2d",n) then it will reserve the output console with 2 character and if the number of digits of n are larger than the specifier then it will print with no spaces, now suppose you print with %6d then what will happen the number of character it will reserve i.e. 6 ...
You can use an asterisk (*
) to pass the width specifier/precision to printf()
, rather than hard coding it into the format string, i.e.
void f(const char *str, int str_len) { printf("%.*s\n", str_len, str); }
More detailed here.
integer value or
*
that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)
.
followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero. See the table below for exact effects of precision.
So if we try both conversion specification
#include <stdio.h> int main() { int precision = 8; int biggerPrecision = 16; const char *greetings = "Hello world"; printf("|%.8s|\n", greetings); printf("|%.*s|\n", precision , greetings); printf("|%16s|\n", greetings); printf("|%*s|\n", biggerPrecision , greetings); return 0; }
we get the output:
|Hello wo| |Hello wo| | Hello world| | Hello world|
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