Formatters in C

1

Hello I was looking at wikipedia the "Formatters" and I hit this code, it is assumed that what I put after the% and before the d will vary the result, but in all cases I printed the complete number 1234 . What are the values that I use for? thank you ..

#include <stdio.h>


int main()
{
    printf("%2d",   1234);  // for 34
    printf("%.2d",  1234);  // for 34
    printf("%-2d",  1234);  // for 12
    printf("%-.2d", 1234);  // for 12
    return 0;   
}
    
asked by EmiliOrtega 13.02.2017 в 16:59
source

1 answer

4

Case 1:

printf("%2d",   1234);

There you are saying that you reserve a minimum of 2 characters to print a value, in this case an integer. If you want to see differences in this case, try assigning a value greater than the number of digits:

printf("%10d",1234);

Case 2:

printf("%.2d",  1234);

In this case you are indicating that you have to print a maximum of two decimals ... but you are working with an integer (which do not have decimals). What happens here is that that configuration is ignored.

Case 3:

printf("%-2d",  1234);

Similar to case 1. In this case not only the minimum size of the field is less than the number of digits but you are also indicating that the value is aligned to the left ... To see the effect of this configuration try to print two values:

printf("%-10d%d",1111,2222);

Case 4:

printf("%-.2d", 1234);

In this case the same thing happens to you as in case 2. The type int has no decimals, then the configuration is ignored.

    
answered by 13.02.2017 в 17:23