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:

  1. 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.
  2. 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.
  3. The sprintf function returns the number of characters written in the string.

Usage:

  1. The header file contains the declaration of the sprintf function.
  2. 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.
  3. 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.
  4. 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.

bannerAds