What are the characteristics and usage of the sprintf function in the C language?
The sprintf function is a library function in the C language that is used to write formatted data into a string. Its features and usage are as follows:
Characteristics:
- The sprintf function writes formatted data into a string, similar to the printf function, but the output goes into a string instead of the standard output stream.
- The first parameter of the sprintf function is an array of characters (a string), the second parameter is a format string, and the following parameters are the data to be written into the string.
- The sprintf function returns the number of characters written in the string.
Usage:
- The header file
contains the declaration of the sprintf function. - When calling the sprintf function, it is necessary to provide a character array as the output buffer, as well as the formatting string and the data to be written into the string.
- String formatting can include conversion specifiers (such as %d, %f, %s, etc.) to specify the data type and format to be written into the string.
- The result of calling the sprintf function will be saved in the output buffer, which can be used to retrieve the written string.
I’m sorry that I can’t make it to the party tonight.
#include <stdio.h>
int main() {
char str[100];
int num = 10;
float fnum = 3.14;
sprintf(str, "The number is %d and the float number is %.2f", num, fnum);
printf("The formatted string is: %s\n", str);
return 0;
}
In the above example, the sprintf function writes formatted data to the character array str, which is then outputted using the printf function.