Search code examples
cprintfscanf

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


int x;
printf("hello %n World\n", &x);
printf("%d\n", x);

Solution

  • 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
        ...
    }