开发者

printf issue in linux

Following is a simple program to print formatted "1.2" on HP & Linux. However, the behavior is different. I do not want to make the question bigger but the program where this is actually occurring has a float value in a string, so using %f is not an option (even using sprintf).

Has anyone encountered this before? Which behavior is correct?

This should not be a compiler issue but still have tried it on gcc, icpc, icc, g++.

#include <st开发者_运维百科dio.h>

int main()
{
   printf("%s = [%010s]\n", "[%010s]",  "1.2");
   return 0;
}

**HP:**
cc test2.c -o t ; ./t
[%010s] = [00000001.2]

**Linux:**
icc test2.c -o t ; ./t
[%010s] = [       1.2]

Edit: Thank you all very much for the responses :)


From the glibc printf(3) man page:

   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.

So a 0 flag with s cannot be expected to pad the string with 0s on glibc-based systems.


According to the man page, the behaviour of the 0 flag for anything other than d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions is undefined. So both are fine.

EDIT: When I say "fine", I mean from the compiler/libc standpoint. From your application's point of view, the behaviour you're relying on (on both Linux & HP) is a bug and you should do your formatted printing correctly.


If you don't want leading zero fill, omit the leading zero fill indicator:

printf("%s = [%10s]\n", "[%010s]",  "1.2");

It is somewhat surprising that an implementation honors filling a string with zeros, but it is easily corrected.


Adding to what Ignacio Vazquez-Abrams said, according to the documentation for printf, the result of what you are doing is undefined behavior. The fact that two OSes produce different results is not unexpected.

In fact, compiling your code with gcc 4.5.2 on Ubuntu gives the following warning:

warning: '0' flag used with ‘%s’ gnu_printf format

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜