4

I do not understand why this is the case:

Printf.sprintf "%08s" "s" = Printf.sprintf "%8s" "s"
- : bool = true

In other words, I would expect:

Printf.sprintf "%08s" "s"
- : string = "0000000s"

and not the actual result:

- : string = "       s"

could someone please clarify why this is so?

mbunit
  • 463
  • 3
  • 10

2 Answers2

5

From the documentation of printf, you can see that the 0 flag does not apply to %s.

0: for numerical conversions, pad with zeroes instead of spaces.

(Emphasis is mine.)

Notice that, in C, it leads to an undefined behavior.

md5
  • 23,373
  • 3
  • 44
  • 93
  • Thank you for the precise, quick answer :) I'll mark it as answered. I seem to have somehow managed to gloss over that important detail in the documentation. Apologies! – mbunit Jan 23 '13 at 22:43
2

When I try your format specifier in C, I get the following warning:

warning: flag '0' results in undefined behavior with 's' conversion specifier

Assuming my compiler isn't crazy (Mac OS X 10.8.2), this would suggest that OCaml's conversion is fine.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108