The Single UNIX Specification Version 2 specifies the sprintf
's format '
-flag behavior as:
The integer portion of the result of a decimal conversion (
%i
,%d
,%u
,%f
,%g
or%G
) will be formatted with thousands' grouping characters[1]
I can't find the format '
-flag in the c or the c++ specifications. g++ even warns:
ISO C++11 does not support the
'
printf
flag
The flag is not recognized to even warn about in Visual C; printf("%'d", foo)
outputs:
'd
I'd like to be able to write C-standard compliant code that uses the behavior of the format '
-flag. Thus the answer I'm looking for one of the following:
- C-Standard specification of the format
'
-flag - A cross platform compatible extrapolation of gcc's format
'
-flag - Demonstration that a cross platform extrapolation is not possible
Standard C doesn't provide the formatting capability directly, but it does provide the ability to retrieve a...specification of what the formatting should be, on a locale-specific basis. So, it's up to you to retrieve the locale's specification of proper formatting, then put it to use to format your data (but even then, it's somewhat non-trivial). For example, here's a version for formatting
long
data:This does have a bug (but one I'd consider fairly minor). On two's complement hardware, it won't convert the most-negative number correctly, because it attempts to convert a negative number to its equivalent positive number with
N = -N;
In two's complement, the maximally negative number doesn't have a corresponding positive number, unless you promote it to a larger type. One way to get around this is by promoting the number the corresponding unsigned type (but it's is somewhat non-trivial).Implementing the same for other integer types is fairly trivial. For floating point types is a bit more work. Converting floating point types (even without formatting) correctly is enough more work that for them, I'd at least consider using something like
sprintf
to do the conversion, then inserting the formatting into the string that produced.