Format string with multiple percent signs

I know what is %%used to avoid the actual characters %in the line, so it %%%dsends with %10sthe next format line, but I don’t know why I need %%5sthis line?

In the end, there are only two additional arguments (BUFFSIZE / 10).

#define BUFFSIZE 100
char buf[100]={0}
sprintf(buf, "%%5s %%%ds %%%ds", BUFFSIZE / 10, BUFFSIZE / 10);

After executing the code above, buf will contain a line,

%10s %10s 
+4
source share
3 answers

The goal is to get a format string in order to use it in another function that needs a format string, for example sscanf().

: %5s %10s %10s, buf, . , , .

%%5s          --> %5s
%%%ds with 10 --> %10s (read it that way: {%%}{%d}{s})

%5s %10s %10s sscanf(), .

, sscanf(), Kernighan Pike , . , SO.


, , , %*s, , . SO:

printf, * , .. printf("%*d", 4, 100); 4.

scanf * , , , scanf("%*d %d", &i) "12 34" 12 34 i.

+5

% . , C11, §7.21.6.1/P2, ( )

%. % :

  • [...]

  • .

  • [...]

  • [...]

  • , .

P8

:

......

%

A % . . %%.

,

 ....   %%%ds, BUFFSIZE / 10 ....

 {%%}{%d}{s}
  ^^--------------------------Replaced as %
      ^^----------------------Actual conversion specification happens, argument is used
         ^^------------------just part of final output

, ,

  %Xs    //where X is the value of (BUFFSIZE / 10)

(%, , , ), .

+2

OP . , %5s %10s %10s, printf scanf:

printf("%5s %10s %10s", "A", "B", "C");

:

    A          B          C

char a[6], b[11], c[11];
scanf("%5s %10s %10s", a, b, c);

3 a, b, c, , , .

, , printf , :

printf("%5s %*s %*s", "A", BUFFSIZE / 10, "B", BUFFSIZE / 10, "C");

, scanf() *, , , .

0
source

Source: https://habr.com/ru/post/1680189/


All Articles