C string padding to separate two strings to fixed width

Viewed 65

I'm trying to print a list in C that lines up the index of the list and a colon to the ouput as follows:

...
8  : SOME STUFF
9  : MORE STUFF
10 : MORE STUFF BUT LESS PADDING
...
100: MORE STUFF BUT NO PADDING
...

I'm currently using:

printf("$%d", index);
printf(":"): // this is the line that needs changing
printf(" some stuff");
1 Answers
int array[] = { 1, 2, 3, 4, 5, 6, 7, 42, 999 };
enum { NUM_ARRAY = sizeof( array ) / sizeof( array[ 0 ] ) };
for ( int i = 0; i < NUM_ARRAY; ++i ){
    printf( "%-3d: sometext\n", array[ i ] );
}

This is a for-loop through an array. Every array-item will be printed with a padding of three.

Output:

1  : sometext
2  : sometext
3  : sometext
4  : sometext
5  : sometext
6  : sometext
7  : sometext
42 : sometext
999: sometext
Related