The use of the sprintf function
1. The function is contained in the header file of the stdio.h.
2, sprintf and usually our usual function of printf function is very similar. The sprintf function prints to the string, and the printf function prints the output to the screen. The sprintf function is widely used in our operations to convert other data types into string types.
3, the format of the sprintf function:
int sprintf (char *buffer, const char *format [, Argument,...]);
In addition to the first two parameters, the optional parameter can be any one. Buffer is the character array name, format is the formatted string (like: "%3d%6.2f% #x%o",% and #, automatically precede the hexadecimal number with 0x). As long as the formatted string can be used in printf, it can be used in sprintf. Where the formatted string is the essence of this function.
4, Char str[20];
Double f=14.309948;
sprintf (str, "%6.2f", f);
Precision can be controlled.
5, Char str[20];
int a=20984,b=48090;
sprintf (str, "%3d%6d", b);
str[]= "20984 48090"
Multiple numeric data can be connected together.
6, Char str[20];
Char s1[5]={' A ', ' B ', ' C '};
Char s2[5]={' T ', ' Y ', ' X '};
sprintf (str, "%.3s%.3s", S1,S2);
Multiple strings can be concatenated into a string
%M.N in the output of the string, m represents the width, the number of columns that the string occupies, and n represents the actual number of characters. %M.N in floating-point numbers, M also represents the width; n represents the number of decimal places.
7, can be dynamically specified, the number of characters to be intercepted
Char s1={' A ', ' B ', ' C '};
Char s2={' T ', ' Y ', ' X '};
sprintf (str, "%.*s%.*s", 2,S1,3,S2);
sprintf (S, "%*.*f", 10, 2, 3.1415926);
8, sprintf (S, "%p", &i);
Can print out the address of I
The above statement is equivalent to
sprintf (S, "%0*x", 2 * sizeof (void *), &i);
9. The return value of sprintf is the number of characters in the character array, that is, the length of the string, without having to call strlen (s) to find the length of the string.
Original Portal: please click
The use of the sprintf () function in C language