I've been trying to cobble together the format of printf
into a sort of linear format. Is the following a correct understanding of the possible printf
formats?
% <justification: [-]?> <sign: [ +]?> <alternate: [#]?>
<padding: [0? num]?> <precision: [.num]?> <modifier: [h|hh|l|ll|L|z|t|j]?>
<format: [c|d(i)|e(E)|f|o|p|x(X)|u|s|g(G)]>
Is the order and meanings correct in the above? A couple examples being:
printf(" %-10.3s %-+20ld", "Hello!", 14L);
Is the following a correct understanding of the possible printf formats?
"Generally" yes, but for example you "can't" do %jg
or like %0#p
.
There is also %n
.
Both "precision" and "padding" may be asterisks, like %*s
or %.*s
(but you could have defined num
as ([0-9]+|\*)
...).
Also .
is optionally followed by a number. So it's more like <precision: [. num? ]>
<precision: [. num? ]>
<precision: [. num? ]>
- if only .
is specified, precision is taken as zero.
Is the order
The order of - +#0
is irrelevant and you can repeat them, so you can %-+020d
and %+0-+++000----20d
with same meaning (and 0
is ignored when used with -
, so also there are corner cases).
meanings correct in the above?
There is no explanation in the above. -
is not "justification" (taken literally, a word?), it's a flag that makes the output be left justified within the field . Also meaning depends on context - "precision" for floats maybe can be understood as the number of digits after comma, but "precision of a string" sounds strange. But generally, yes.
Your specification is too restrictive:
+
, -
, #
, 0
and space can appear in any order, but some combinations are meaning less, such as %+s
.*
a
and A
were introduced to produce hexadecimal floating point representationsF
is available and different from f
for NaNs and infinities.%%
and %n
should be recognised too. Here is a regular expression to match all valid printf
conversion specifications, but that will not detect invalid combinations:
%[ +-#0]*{[*]|[1-9][0-9]*}?(.{[*]|[0-9]*}?)?{h|hh|l|ll|L|z|t|j}?[%naAcdieEfFopxXusgG]
You might refine it to reject any flags for %%
and restrict other cases too, but it will become quite complicated to express as a regex.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.