What is the use of the %n
format specifier in C? Could anyone explain with an example?
In C, %n is a special format specifier. In the case of printf() function the %n assign the number of characters printed by printf(). When we use the %n specifier in scanf() it will assign the number of characters read by the scanf() function until it occurs.
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 above program prints “geeks for geeks 10”.
The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.
Most of these answers explain what %n
does (which is to print nothing and to write the number of characters printed thus far to an int
variable), but so far no one has really given an example of what use it has. Here is one:
int n; printf("%s: %nFoo\n", "hello", &n); printf("%*sBar\n", n, "");
will print:
hello: Foo Bar
with Foo and Bar aligned. (It's trivial to do that without using %n
for this particular example, and in general one always could break up that first printf
call:
int n = printf("%s: ", "hello"); printf("Foo\n"); printf("%*sBar\n", n, "");
Whether the slightly added convenience is worth using something esoteric like %n
(and possibly introducing errors) is open to debate.)
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