Addresses, Pointers, Arrays and Strings - The library function sprintf() and puts()

Chapter chap6 section 13

The library function sprintf() is similar to printf() only the formatted output is written to a memory area rather than directly to standard output. It is particularly useful when it is necessary to construct formatted strings in memory for subsequent transmission over a communications channel or to a special device. Its relationship with printf() is similar to the relationship between sscanf() and scanf(). The library function puts() may be used to copy a string to standard output, its single parameter is the start address of the string. puts() writes a new-line character to standard output after it has written the string.

A simple example of the use of sprintf() and puts() is shown below.

main()
{
	char	buf[128];
	double	x = 1.23456;
	char	*spos = buf;
	int	i = 0;
	sprintf(buf,"x = %7.5lf",x);
	while(i<10) puts(spos+i++);
}
producing the output
x = 1.23456
 = 1.23456
= 1.23456
 1.23456
1.23456
.23456
23456
3456
456
56
If "\n" had been incorporated in the format string of the sprintf() then the output would have been double spaced because the sprintf() function would have put a newline character in the generated string and puts() would then generate a further newline.

Note that this program is slightly naughty, strictly sprintf()' s layout specification string should be a string constant.

The correct way to adjust field width and precision at run time is to replace the width and/or precision with a star ("*") and include an appropriate integer in the parameter list. This value will be used before the actual value to be converted is taken from the parameter list. Here is a program showing the facility in use.

main()
{
	double  x=1234.567890;
	int     i=8,j=2;
	while(i<12)
	{
		j=2;
		while(j<5)
		{
			printf("width = %2d precision = %d "
			       "display >>%*.*lf<<\n",i,j,i,j,x);
			j++;
		}
		i++;
	}
}
The program displays the effects of various widths and precisions for output of a double variable. Here is the output.
width =  8 precision = 2 display >> 1234.57<<
width =  8 precision = 3 display >>1234.568<<
width =  8 precision = 4 display >>1234.5679<<
width =  9 precision = 2 display >>  1234.57<<
width =  9 precision = 3 display >> 1234.568<<
width =  9 precision = 4 display >>1234.5679<<
width = 10 precision = 2 display >>   1234.57<<
width = 10 precision = 3 display >>  1234.568<<
width = 10 precision = 4 display >> 1234.5679<<
width = 11 precision = 2 display >>    1234.57<<
width = 11 precision = 3 display >>   1234.568<<
width = 11 precision = 4 display >>  1234.5679<<
The ">>" and "<<" are used to indicate the limits of the output field. Note that the variables "i" and "j" appear twice in parameter list, the first time to give the values in the annotation and the second time to actually control the output.


Arrays of Strings