Home > OS >  c which format is used in this swprintf()
c which format is used in this swprintf()

Time:04-14

What format does this specify in int swprintf (wchar_t* ws, size_t len, const wchar_t* format, ...); ?

L"x.4x "

CodePudding user response:

A break-down of the parts:

  • the L prefix specifies a wide format string (wchar_t *, as opposed to char * in [s]printf)
  • the leading x is not part of the format specifier, same as the trailing space
  • %x results in a hexadecimal representation of the argument
  • the 0 specifies the padding - i.e., if the given number is less than the specified number of digits (see next bullet point), it will be padded with 0s
  • the 4 after that gives the width, i.e. the printed number of digits (but including extra characters such as 0x, in case for example the # prefix would have been given as well)
  • .4 - 'precision' for floating points, for integers it is the (minimum) number of printed digits

See also for example this answer, and myriads of other format specifier resources, e.g. on cppreference

Note that the combination of a width and a precision can lead to unexpected results; the precision is considered for the number of digits (including the number of 0), and the width is used for the width of the resulting string; examples:

wprintf(L"x%2x\n", 0x618);
wprintf(L"x%.2x\n", 0x618);
wprintf(L"x%0.3x\n", 0x0618);
wprintf(L"x%0.4x\n", 0x0618);
wprintf(L"x.4x\n", 0x618);
wprintf(L"x.4x\n", 0x618);
wprintf(L"x0.4x\n", 0x618);
wprintf(L"x0x\n", 0x618);

Output:

x618
x618
x618
x0618
x0618
x0618
x    0618
x00000618

So as you can see, a "width" less than 4 doesn't change anything about the output, unless the precision also decreases (but a precision less than 3 also does not decrease the number of digits shown, as it wouldn't be possible to represent the number with less digits).

And in the next-to-last line, you see the effect of a large value for width but low precision; the output is right-aligned, but with spaces instead of 0 as prefix.

  • Related