Search code examples
cprintfplaceholderturbo-c

When I use the asterisk to indicate the field width, how come it is missing one space?


printf("12345678\n");
printf("%*c%*c, 2, 'a', 2, 'b');

On the console, I was expecting that a would be below 3 and b below 6 since the way I understand it is that I indicated two spaces before each character. However, the output shows that a is below 2 and, b is below 4.


Solution

  • The reason for that, is that the number in front of a format specifier defines the field width not a margin or a padding. In the format %ns, where n is an integer number and s is your specifier of choice, n defines that you are reserving n spaces for what ever you will replace the specifier with. That said, if the information which replaces the specifier will need more than n spaces, it will take the spaces it needs.

    So if you want the letters a and b to appear below 3 and 6 you need to reserve three spaces for each letter not two.

    printf("%*c%*c, 3, 'a', 3, 'b');