coutputprintfconversion-specifier

How to align tabular data to the left with printf?


Let us suppose that we want to display different values aligned in a tabular way, in C, using printf.

We can do something like this:

#include <stdio.h>
int main()
{
    char strings[5][10] = {"Test1","Test2","Test3","Test4","Test5"};
    int ints[5] = {1,2,3,4,5};
    float floats[5] = {1.5,2.5,3.5,4.5,5.5};
    int i;
    printf("%10s%10s%10s\n","Strings","Ints","Floats");
    for(i=0;i<5;i++){
        printf("%10s%10d%10.2f\n",strings[i],ints[i],floats[i]);
    }
    return 0;
}

In this example, we have 5 strings, 5 ints, and 5 floats. At each line, I would like to display them aligned. This piece of code does this. However, the data is aligned to the right. We can see the result in the following image:

enter image description here

How can I do something like this, but aligning the data to the left?


Solution

  • Use the flag '-' in the format strings like

        printf( "%-10s%-10s%-10s\n", "Strings", "Ints", "Floats" );
        for (i = 0; i < 5; i++) {
            printf( "%-10s%-10d%-10.2f\n", strings[i], ints[i], floats[i] );
        }
    

    From the C Standard (7.21.6.1 The fprintf function)

    6 The flag characters and their meanings are:

    '-' The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)