Sprintf in C:
1. This function is included in the stdio.h header file.
2. Sprintf functions is similar to the printf function . The sprintf function prints to a string, while the printf function prints output to the screen.
Sprintf function is widely used in the operation.
The format of Sprintf function:
int sprintf (char * buffer, const char * format [, argument, …]);
In addition to the first two required parameters, optional parameter can be an arbitrary number.
buffer is a character array;
format is the format string (like: “% 3d% 6.2f% # x% o% and # in combination). As long as the format string can be used in the printf, it also can be used in sprintf.The format string is the necessary part of this function.
Example 1:
char str [20];
double f = 14.309948;
sprintf (str, “% 6.2f”, f);
Example 2:
char str [20];
int a = 20984, b = 48090;
sprintf (str, “% 3d% 6d”, a, b);
str [] = “20984 48090”
It can be used to concatenate two numbers as strings.
Example 3:
char str [20];
char s1 [5] = {‘A’, ‘B’, ‘C’};
char s2 [5] = {‘T’, ‘Y’, ‘x’};
sprintf (str, “% .3 s% .3 s”, s1, s2);
Multiple strings can be concatenated to a long string.
%Mn in the output string, m width, tcharacter string; n is the actual number of characters . %m.n in the floating-point , m width; n represents the number of decimal places.
Example 4:
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);
You can print out the i address
The above statement is equivalent to
sprintf (s, “% 0 * x”, 2 * sizeof (void *), & i);
Sprintf returns value is the number of characters in the character array, that is, the length of string, do not call strlen (s) to find the length of string.
Leave a Reply
You must be logged in to post a comment.