In the process of solving problems, I came across this code snippet for formatting output: printf("%*s%s%*s\n",__________);
The required output format is: ________123456________
//The underscores represent spaces
At that time, I found it strange because I had never seen the %*s
usage before, and I was puzzled, thinking that it outputs a string pointer. However, outputting so many spaces did not seem scientific.
My first attempt was written like this:
1 | printf("%*s%s%*s\n"," ","132456"," "); |
It didn’t throw an error, but the result was incorrect (the output was garbled).
Finally, I remembered this way of formatting string output:
1 | printf("%8s%s%8s"," ","132456"," "); |
The output format was very standard: (________123456________
)//The underscores represent spaces
Then the problem was how to make the output formats of the following two lines of code consistent:
1 | printf("%*s%s%*s\n"," ","132456"," "); |
After flipping through books, I found in C Primer Plus
Fourth Edition, P81, 4.4.6 printf() and scanf() * modifier
states:
Both printf() and scanf() can use the * modifier to modify the meaning of the specifier, but their methods are different.
Printf Usage
Suppose you do not want to specify the character width in advance but want the program to specify that value, then you can use the * modifier to achieve this.
Code example: Suppose number=123.4
1 | scanf("%d%d",&width,&precision); |
Testing this piece of code:
Input: 8 3
Output: __123.400
//The underscores represent spaces
%8.3f means the field width (including the decimal point) is 8, of which the part after the decimal point occupies 3 digits.
Similarly, when outputting a string, the * modifier
can also be understood as:printf("%*s",10,"a");
Output: (
_________a
)//The underscores represent spaces
This outputs a field width of ten characters.
If the code is like this: printf("%*s",-10,"a");
Output: (
a_________
)//The underscores represent spaces
It can be seen that the sign of the * modifier parameter is similar to left and right alignment formats.
Thus, the output format of %*s
should be:
printf(“%*s”,
total field width
, “string to output
“);
Now looking back at the required output format:
Code:
printf("%*s%s%*s\n",__________);
The required output format is:________123456________
//The underscores represent spaces
It can be seen that we need to output a field width of 8 spaces before the string 123456
, so we can know that the output parameters for the first %*s
are 8, " "
, then output the string 123456
, and the same is needed for the field width of 8 characters after, thus the parameters are the same as those of the first %*s
.
The implementation code is:
1 | printf("%*s%s%*s",8," ","132456",8," "); |
Output: (________123456________
)