Left-pad printf with spaces

前端 未结 4 1091
深忆病人
深忆病人 2020-11-29 21:20

How can I pad a string with spaces on the left when using printf?

For example, I want to print \"Hello\" with 40 spaces preceding it.

Also, the string I want

4条回答
  •  借酒劲吻你
    2020-11-29 21:57

    int space = 40;
    printf("%*s", space, "Hello");
    

    This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows:

    printf("%*d", space, 10);
    printf("%*c", space, 'x');
    

    This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:

    printf("%*d", 10, 10);
    printf("%*c", 20, 'x');
    printf("%*s", 30, "Hello");
    

    Hope this helps someone like me in future.

提交回复
热议问题