C++ sprintf Function Explained

The sprintf function is a function in the C++ standard library that is used to write formatted data to a string.

In specific terms, the sprintf function converts various types of data (such as integers, floating-point numbers, strings, etc.) into string form according to a specified format and writes them into a designated character array. This can be used to create strings with specific formats, such as converting numbers into strings and adding units, or formatting the values of multiple variables into a single line.

The prototype of the sprintf function is:

int sprintf ( char * str, const char * format, ... );

In this case, str is a pointer to a character array used to store the formatted string; format is a parameter that controls the string format and consists of a string composed of “% (format specifier)”; the following … represents variable arguments used to pass in the data to be formatted.

Here is an example demonstrating how to use the sprintf function:

#include <cstdio>

int main() {
    char str[100];
    int num = 10;
    float f = 3.14;
    sprintf(str, "The number is %d and the float is %.2f", num, f);
    printf("%s\n", str);
    return 0;
}

Output:

The number is 10 and the float is 3.14

In the example above, the sprintf function converts the integer num and the floating-point number f to strings according to the specified format and writes them into the character array str. Finally, the printf function prints out str.

bannerAds