Correction: this isn't always the best way to setup columns.
There are two starting points for making columns: you can either choose a column header and then make columns, or choose column widths and then make a column header. The example below details the way of making a column header first and then deciding your column widths. Hopefully, both ways can be clear by the end of this webpage.
Suppose that this is the output you want:
Column1 Column2 Column3
|
Now, look at each character. Spaces are shown as underscores (_) below.
C | o | l | u | m | n | 1 | _ | _ | _ | _ | C | o | l | u | m | n | 2 | _ | _ | _ | C | o | l | u | m | n | 3 |
_ | _ | _ | _ | 1 | 0 | 0 | _ | _ | _ | _ | _ | _ | _ | 1 | 2 | 2 | 1 | _ | _ | _ | _ | _ | _ | 9 | 3 | 4 | 8 |
_ | _ | _ | _ | _ | 2 | 3 | _ | _ | _ | _ | _ | _ | _ | _ | 2 | 1 | 1 | _ | _ | _ | _ | _ | _ | _ | 2 | 1 | 4 |
Each column is color-coded so you can see that column one is 7 characters wide, column two is 11 characters wide, and column three is 10 characters wide.
The code to generate this would look like:
printf("Column1 Column2 Column3\n");
printf("%7d%11d%10d\n", 100, 1221, 9348);
printf("%7d%11d%10d\n", 23, 211, 214);
Notice that the %7d
goes with values from the first column, %11d
goes with values from the second column, and %10d
goes with values from the third column. The reason d
is used is because we're using integers. If you were writing your own code, you'd probably have variable names instead of the numbers there.
Suppose that I change the numbers slightly so that they have decimal places:
Column1 Column2 Column3
|
So there's one decimal place in the first column, none in the second, and three in the third.
Then I would have code that looks like this:
printf("Column1 Column2 Column3\n");
printf("%7.1lf%11.0lf%10.3lf\n", 100.1, 1221.0, 9348.012);
printf("%7.1lf%11.0lf%10.3lf\n", 2.3, 211.0, 214.0);
It's important to note that the values in the printf
statement have to match the data type in the string in the first part of the printf statement. So if you're using variables of type double
, use lf
. Even more important to note is that the numbers 7, 11, and 10 didn't change.
printf
statement to show one row might look like:
printf("%7d%8d%8d", 1, 2, 3);
%-7d
instead of %7d