Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any practical applications for the format %n in printf/scanf family?

Tags:

c

printf

scanf

int x;
printf("hello %n World\n", &x);
printf("%d\n", x);
like image 888
EvilTeach Avatar asked Dec 09 '08 17:12

EvilTeach


People also ask

What is use of %n in printf ()?

In C language, %n is a special format specifier. It cause printf() to load the variable pointed by corresponding argument. The loading is done with a value which is equal to the number of characters printed by printf() before the occurrence of %n.

What is %n Sscanf?

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. Key points: It is an edit conversion code.

What is %A in printf?

The %a formatting specifier is new in C99. It prints the floating-point number in hexadecimal form. This is not something you would use to present numbers to users, but it's very handy for under-the-hood/technical use cases. As an example, this code: printf("pi=%a\n", 3.14); prints: pi=0x1.91eb86p+1.


1 Answers

It's not so useful for printf(), but it can be very useful for sscanf(), especially if you're parsing a string in multiple iterations. fscanf() and scanf() automatically advance their internal pointers by the amount of input read, but sscanf() does not. For example:

char stringToParse[256];
...
char *curPosInString = stringToParse;  // start parsing at the beginning
int bytesRead;
while(needsParsing())
{
    sscanf(curPosInString, "(format string)%n", ..., &bytesRead);  // check the return value here
    curPosInString += bytesRead;  // Advance read pointer
    ...
}
like image 72
Adam Rosenfield Avatar answered Nov 16 '22 02:11

Adam Rosenfield