Search code examples
c++printfcolumn-width

printf with a width modifier fails to print the value


In a C++ program, under Windows 7 using VS2013 and under Ubuntu 14.04.1 using g++ 4.6, I am mystified by the operation of printf().

With the 2nd width modifier, this prints a space instead of a 0.
When set to another value, e.g., -1, it prints it. Without the modifier, it prints a 0, as expected.

I pasted the actual, relevant code into another program and it behaved the same way.

What could be the problem?

#include <stdio.h>

int main(){
    int x = 1, z = 0;
    printf ("%2.d: %2.d\n", x, z); // fails to print 0
    printf ("%2.d: %d\n", x, z);  // 2nd %2. absent, prints as expected
    return 0;
}

Output:

 1:   
 1: 0

Solution

  • The point should go to the left

    #include <stdio.h>
    
    int main()
    {
        int x = 1, z = 0;
        printf ("%.2d: %.2d\n", x, z); // fails to print 0
        printf ("%.2d: %d\n", x, z);  // 2nd %2. absent, prints as expected
        return 0;
    }
    

    Output:

    01: 00
    01: 0