C++ sprintf Function: Complete Guide
The sprintf function in C++ is used to write formatted data into a string. Its basic syntax is as follows:
int sprintf(char* str, const char* format, ...);
In this case, str refers to a pointer to the target string, while format contains a constant string with the formatting characters. The ellipsis (…) signifies variable arguments, which are used to specify the data that needs to be written based on the format characters in the formatting string.
The sprintf function converts data into a string based on the format specifiers in the format string, and writes the result into the string pointed to by str. It is similar to the printf function, but instead of printing the result to the standard output stream, it writes the result into the string. The sprintf function returns the number of characters written into the string (excluding the null termination character ‘\0’).
Here is an example demonstrating how to use the sprintf function:
#include <cstdio>
int main() {
char str[50];
int num = 10;
float f = 3.14;
sprintf(str, "Integer: %d, Float: %.2f", num, f);
printf("%s\n", str);
return 0;
}
The output result is:
Integer: 10, Float: 3.14
In the above example, the sprintf function converts the integer num and floating point f to strings based on the format specifiers in the formatting string, and writes the result to the string pointed to by str. Finally, the printf function outputs the string to the standard output stream.