What does "% 3d" mean in a printf expression?

In this code, what is the role of the %3d symbol? I know that% means a reference to a variable.

This is the code:

 #include <stdio.h> int main(void) { int t, i, num[3][4]; for(t=0; t<3; ++t) for(i=0; i<4; ++i) num[t][i] = (t*4)+i+1; /* now print them out */ for(t=0; t<3; ++t) { for(i=0; i<4; ++i) printf("%3d ", num[t][i]); printf("\n"); } return 0; } 
+4
source share
8 answers

%3d can be broken as follows:

  • % means "Print variable here"
  • 3 means "use at least 3 spaces to display, filling if necessary"
  • d means "the variable will be integer"

Combining them, it means "Print an integer that takes at least 3 spaces"

See http://www.cplusplus.com/reference/clibrary/cstdio/printf/ for more details.

+16
source

This is the format specifier for printing decimal ( d ) in three (at least) digits ( 3 ).

From man printf :

An optional decimal digit string indicating the minimum field width. If the converted value is less than the width of the field, it will be padded with spaces on the left (or on the right if the left setting flag was given) to fill the field with width.

+11
source

Take a look here:

Print("%3d",X);

  • If X is 1234, it prints 1234 .
  • If X is 123, it prints 123 .
  • If X is 12, it prints _12 , where _ is the leading single space character.
  • If X is 1, it prints __1 , where __ are the two leading characters of whitespacce.
+4
source

This is a formatting specification. % 3d says: type the argument as a decimal, 3 digits wide.

0
source

In the literal sense, this means that you need to print an integer with three digits with spaces. % Enters a format specifier, 3 stands for 3 digits, and d stands for an integer. Thus, the value num [t] [i] is displayed as a value such as โ€œ1โ€, โ€œ2โ€, โ€œ12โ€, etc.

0
source

2/3 or any integer is padding / width.it means ex for 3, at least 3 spaces, if we print a = 4, then it prints as 4, here there are two spaces left up to 4, because it is one character

0
source

Example to enlighten existing answers:

 printf("%3d" , x); 

When:

x - 1234 prints 1234

x - 123 prints 123

x - 12 prints 12 with additional filling (space)

x - 1 fingerprint 1 with two additional paddings (spaces)

0
source

You can specify a field width between% and d (for decimal). It represents the total number of characters printed. A positive value, as mentioned in another answer, aligns the output to the right and is the default value. A negative value aligns the text to the left. example:

 int a = 3; printf("|%-3d|", a); 

Exit:

 |3 | 

You can also specify the field width as an additional parameter using the * character:

 int a = 3; printf("|%*d|", 5, a); 

which gives:

 | 3| 
0
source

Source: https://habr.com/ru/post/1309356/


All Articles