Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf format specifiers

Tags:

c

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);
like image 452
samuelbrody1249 Avatar asked Nov 23 '25 21:11

samuelbrody1249


1 Answers

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? ]> - 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.

like image 190
KamilCuk Avatar answered Nov 26 '25 11:11

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!