C programming sprintf stdio.h

In C programming the <stdio.h> sprintf function output the data to the specified array instead of the stream.The declaration of the function is given below.

int snprintf(char * restrict s ,
const char * restrict format, …);

s -This array stores the outputted data.

format -The data with the conversion specifier that is to be written to ‘s’.

-An ellipsis that consists of the variable names.

Return type
int -Returns the number of characters written to the array not counting the terminating null character,or a negative value f an encoding error occurred.

***Note ‘sprintf’ is equivalent to ‘fprintf’ except that snprintf output the data to an array rather output than to a stream.

Link : C fprintf stdio.h

Code example

size_t ret;

char c[30] , str[ ]=”Happy C++ programming!” ;

ret=snprintf(c , n, “Name=%s “, str);

printf(“ret=%d”, ret );

printf(“\n\nc \”%s\”” , c);
printf(“\nc string length=%d”, strlen(c) );



c “Day=Happy C++ programming! ”
c string length=27

Here you can see that the null terminating character is not counted and so the returned value is 27.

*Side Note

The only difference between ‘snprintf’ and ‘sprintf’ is ‘snprintf’ has a quantity-the second argument- that specify the number of characters written to the array,while sprintf has no such thing.In ‘sprintf’ if the size of the array is smaller than the number of characters written to it an unexpected error may occur,so always make sure that the array is big enough to hold the outputted string.

Related links

->C printf stdio.h

->C snprintf stdio.h

->C vsprintf stdio.h