This c code I wrote below to centre text in strings works. I cannot find an explanation of what "%%%ds" in the program means and how it works. There is d for int and s for string but the three percentage symbols is obscure to me. What does "%%%ds" mean and how does it work?
/************************************************
formattCentre.c
example of formatting text to centre
************************************************/
#include<stdio.h>
#include<string.h>
char *verse[] =
{
"The quick brown fox",
"Jumps over the lazy dog",
NULL
};
int main()
{
char **ch_pp;
/* centre the data */
for ( ch_pp = verse; *ch_pp; ch_pp++ )
{
int length;
char format[10];
length = 40 + strlen ( *ch_pp ) / 2; /* calculate the field length */
sprintf ( format, "%%%ds\n", length ); /* make a format string. */
printf ( format, *ch_pp ); /* print the lines*/
}
printf( "\n" );
}
After this call
sprintf ( format, "%%%ds\n", length );
the string format will look like
"%Ns\n"
where N is the value of the expression length.
The two adjacent symbols %%
are written in the string format as one symbol %
.
From the C Standard (7.21.6.1 The fprintf function)
8 The conversion specifiers and their meanings are:
% A % character is written. No argument is converted. The complete conversion specification shall be %%
Try this simple demonstration program.
#include <stdio.h>
int main( void )
{
char s[2];
sprintf( s, "%%" );
puts( s );
}
Its output is
%
So the next call of printf will look like
printf ( "%Ns\n", *ch_pp );