Skip to content
Prev 8967 / 15075 Next

Unexpected behavior from sprintf()

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 12-04-24 04:24 PM, Joran Elias wrote:
on Ubuntu 10.04 (r-devel):
[1] "    1"
[1] "00001"
?sprintf says:

 ?0? For numbers, pad to the field width with leading zeros.

"man 3 printf" on Ubuntu 10.04 says:

       0      The  value  should  be  zero padded.  For d, i, o, u, x,
X, a, A, e, E, f, F, g, and G conversions, the converted value is
padded on the left with zeros rather than blanks.  If the 0 and -
flags  both  appear,  the  0  flag  is ignored.   If  a precision is
given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is
ignored.  For other conversions, the behavior is undefined.

  From a lawyerly point of view, ?sprintf is not wrong.  It defines
the behavior for numbers and fails to define it for non-numbers -- so
technically

ZZZZ1

would also be 'correct' (or at least 'not wrong') output for this case.


printstr.c
============================
#include <stdio.h>

int main() {


   printf("%05s\n","1");
}
==========================


under Ubuntu:

gcc printstr.c
printstr.c: In function ?main?:
printstr.c:6: warning: '0' flag used with ?%s? gnu_printf format
bolker at ubuntu-10:~/R/misc$ ./a.out
    1


under OS X:

 gcc printstr.c
printstr.c: In function ?main?:
printstr.c:6: warning: '0' flag used with ?%s? printf format
collywobbles:misc bolker$ ./a.out
00001


  So we do get a compile-time warning in either case.

  Perhaps the R documentation should waffle about platform-specificity
some more ...


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJPlxGHAAoJED2whTVMEyK9i08IAKuIKvn85nOx8tZm4YhiTKpx
PCB85vjgNkqMxwwmWmJcCf9ixtT7LFpHE//RX6tYZlQPlqcSnOraQNlE3NyEi4qs
g8yovUz5iMtDWF4Wei3a9cL39oKm/bI+L+A2Je8KhlfKDzaa0OtJz+N4Ve4gSut+
/2TiKtfy7ivTRcjmu8RM4hjjELD+9yejZAzQT8WsZrGGl5yzhUcnr+grJFtA3lnD
x08D/eI2Njh1Z4/8Q5FOI2h3dtE7wq8dMDWgHpCuYX0g+HfVo2uk226s2+SXZ6Tj
BRHSS20LU6pBhoplDmhBF71bJZantZMR5J3vHI4lpjpTEHa1xgq8I/HuzL1LhOI=
=9G04
-----END PGP SIGNATURE-----