Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of the %n format specifier in C?

What is the use of the %n format specifier in C? Could anyone explain with an example?

like image 894
josh Avatar asked Aug 03 '10 22:08

josh


People also ask

What is the use of %n in C?

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.

What does %n Do 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. The above program prints “geeks for geeks 10”.

What is %s format specifier in C?

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.


1 Answers

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.)

like image 164
jamesdlin Avatar answered Oct 14 '22 00:10

jamesdlin