Basically I want to print something like this:
Process No.(Size) Block No.(Size)
1(200) 3(300)
2(3) 1(50)
3(1000) 4(1200)
Since the spacing is variable, how to do it by the width specifier in %d
?
printf("%d(%d)%d(%d)",processNo,processSize,blockNo,blockSize)
Where to put the spacing value?
You can first print each 'field' of your table into a character string, then print each such field string using a left-justified, fixed-width format specifier. The latter is accomplished using the -
flag and a width
value in the %s
format specifier (i.e., -n%s
).
The following code displays what you require (I have used the fields to hold both the column titles and each row of data, but this is an 'optional extra').
#include <stdio.h>
int main(void)
{
// Test data ...
int procNo[3] = { 1, 2, 3 };
int procSize[3] = { 200, 3, 1000};
int blockNo[3] = { 3, 1, 4 };
int blockSize[3] = { 300, 50, 1200 };
char procField[32] = "Process No.(Size)";
char blockField[32] = "Block No.(Size)";
// Print rubric ...
printf("%-22s%-22s\n", procField, blockField);
// Print data rows ...
for (int i = 0; i < 3; ++i) {
// Write each field to string ...
snprintf(procField, sizeof(procField), "%d(%d)", procNo[i], procSize[i]);
snprintf(blockField, sizeof(blockField), "%d(%d)", blockNo[i], blockSize[i]);
// ... then print fields as left-justified, fixed-length fields
printf("%-22s%-22s\n", procField, blockField);
}
return 0;
}