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
", "hello", &n);
printf("%*sBar
", 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
");
printf("%*sBar
", n, "");
Whether the slightly added convenience is worth using something esoteric like %n
(and possibly introducing errors) is open to debate.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…