Sprintf C – Writing Formatted Data in String in C or C++
sprintf in C is used to write formatted data to string. The sprintf C writes into the array. The array is pointed by str a C string that consists of a sequence of data formatted according to the format specifued by the argument.
Parameters in Sprintf C
After the format parameter in Sprintf, the sprintf function expects at minimum as many more arguments as mentioned in the format.
The sprintf function behaves similar to the famous printf statement in C, but its writes the results into a string instead of writing to stdout. It therefore redirects the output to a string. In sprintf, the size of the passed array should be big enough to have the entire formatted string.
Semantics of sprintf C
Here are the semantics of the sprintf C statement
int sprintf ( char * pstr, const char * pformat, … );
Return Value of Sprintf
On success, the sprintf returns the number of characters written. This return count excludes additional null-character which gets appended automatically at the end of the string.
On failure, the sprintf returns a negative number. This can be used for error checking.
/* And Example of the sprintf statement*/
#include
int main ()
{
char pbufferx [60];
int num, a1=5, b1=3;
num=sprintf (pbufferx, “%d plus %d is %d”, a1, b1, a1+b1);
printf (“[%s] is a %d char long stringn”,pbufferx,num);
return 0;
}
The program give the output – [5 plus 3 is 8] is a 13 char long string.
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.