Search code examples
cprintflibc

Is this possible with printf?


I understand that, with an oversize string, you can print out the first few characters with:

printf(".5s\n",string);

and with an undersize string, you can pad it with space:

printf("% 5s\n",string);

Is there a way to achieve both of these at once? i.e. pad it with 0 or space if it's short, and truncate it if it's long?


Solution

  • Yes, you can just combine it to this:

    printf("%5.5s\n", string);
    

    So if your string is 1, the output is:

        1
    //^ 4 Spaces here
    

    And if your string is 123456, the output is:

    12345
       //^ 6 doesn't get displayed
    

    Also for more information about printf() and as a reference see this link: http://www.cplusplus.com/reference/cstdio/printf/