Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf issue in linux

Tags:

linux

printf

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 <stdio.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 :)

like image 374
Sudeep Avatar asked Dec 28 '22 14:12

Sudeep


1 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.

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

like image 100
Ignacio Vazquez-Abrams Avatar answered Jan 13 '23 08:01

Ignacio Vazquez-Abrams