Why I can't print 0 with %7.d or other %x.d in C

Viewed 107

Can someone help me in printing 0 with %x.d i.e. %1.d, %2.d, %3.d, etc. Actually if I'm printing 0 with %7.d and it is not showing on terminal. You can visit My GitHub for more reference.

#include <stdio.h>

int main() {
    int num_1 = 0;
    int num_2 = 10000;
    int num_3 = 999;

    printf("Value of \'num_1\' is = %7.d\n", num_1);
    printf("Value of \'num_2\' is = %7.d\n", num_2);
    printf("Value of \'num_3\' is = %7.d\n", num_3);
    return 0;
}
1 Answers

The printf conversion specifier %7.d, equivalent to %7.0d, will convert an argument of type int to its decimal representation with at least 0 digits and pad it with initial spaces up to at least 7 characters.

As a special case, converting the argument value 0, yields no digits and the output will be seven spaces.

You probably do not want these semantics as you expect 0 to produce 0, so you should not specify a precision field with a .. Use %7d instead.

Note also that the \ in front of ' is not required in a C string, but it is in the C character constant '\''

Here is a modified version:

#include <stdio.h>

int main() {
    int num_1 = 0;
    int num_2 = 10000;
    int num_3 = 999;

    printf("Value of 'num_1' is = %7d\n", num_1);
    printf("Value of 'num_2' is = %7d\n", num_2);
    printf("Value of 'num_3' is = %7d\n", num_3);
    return 0;
}

Output:

Value of 'num_1' is =       0
Value of 'num_2' is =   10000
Value of 'num_3' is =     999
Related