Can specifiers align text?

Yes, format specifiers in the printf() function can be used to align text when printing strings and numbers. You can control the alignment by specifying the width of the field and using a minus sign (-) for left alignment. Here are some examples:

  1. Right Alignment (Default): By default, numbers and strings are right-aligned within the specified width.

    printf("%10s\n", "Hello"); // Right-aligned in a field of width 10
    printf("%5d\n", 42);        // Right-aligned integer in a field of width 5
    

    Output:

        Hello
     42
    
  2. Left Alignment: To left-align the output, you can use the minus sign (-) before the width.

    printf("%-10s\n", "Hello"); // Left-aligned in a field of width 10
    printf("%-5d\n", 42);        // Left-aligned integer in a field of width 5
    

    Output:

    Hello     
    42   
    

In these examples, the text and numbers are aligned according to the specified width, and the minus sign indicates left alignment. This allows for better formatting of output, especially when displaying tables or lists.

0 Comments

no data
Be the first to share your comment!