Printf problem in Linux

The following is a simple program to print formatted "1.2" on HP and Linux. However, the behavior is different. I don’t want the question to be bigger, but the program where this happens has a float value in the string, so using% f is not an option (even using sprintf).

Has anyone come across this before? Which behavior is correct?

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

#include <stdio.h> int main() { printf("%s = [%010s]\n", "[%010s]", "1.2"); return 0; } **HP:** cc test2.c -ot ; ./t [%010s] = [00000001.2] **Linux:** icc test2.c -ot ; ./t [%010s] = [ 1.2] 

Edit: Thanks so much for the answers :)

+4
source share
4 answers

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. 

This means that the flag 0 with s cannot insert a row with 0 into glibc-based systems.

+7
source

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

EDIT: When I say "excellent", I mean from the point of view of the / libc compiler. From the point of view of your application, the behavior you rely on (both Linux and HP) is a mistake and you must format the print correctly.

+2
source

If you do not need an initial zero fill, lower the zero fill indicator:

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

Surprisingly, the implementation executes a line with zeros, but it is easy to fix.

+1
source

Adding to what Ignacio Vasquez-Abrams said, according to the documentation for printf , the result of what you do is undefined behavior. The fact that the two operating systems produce different results is not unexpected.

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

warning: flag '0' used in the format '% s gnu_printf

0
source

All Articles