'Using buffer formed from sprintf as a input to sscanf

#include <stdio.h>
int main()
{
    char buffer[50];
    int a = 10, b = 20;
    sprintf(buffer, "%%%dd %%%dd %%%ds", a ,b ,5);
    printf("%s\n", buffer);
    return 0;
}

Currently it is printing: %10d %20d %5s

I need it to print as: %d %d %5d

as this buffer is used as a format in sscanf. not sure about the integer length which will be passed in string input in sscanf.

Not sure what to pass instead of a and b

Please help...



Solution 1:[1]

I need it to print as: %d %d %5d

sprintf( buffer, "%%d %%d %%%dd", 5 );

If you want to print a literal '%', you need to give "%%" ("escaped percent") in the format string. The rest works as normal:

  • "%%d" is
    • "%", followed by
    • "d"

And:

  • "%%%dd" is
    • "%", followed by
    • a decimal from the argument list, followed by
    • "d"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1