What is the purpose of sprintf() function?

The sprintf() stands for “string print.” The sprintf() function does not print the output on the console screen. It transfers the data to the buffer. It returns the total number of characters present in the string.

In C, the sprintf() function is used to format and store a series of characters and values into a string. Its purpose is to perform formatted output to a string. It takes the same arguments as printf(), but instead of printing the formatted string to the standard output (usually the console), it stores the output as a string in a buffer.

For example:

c
#include <stdio.h>

int main() {
char buffer[100];
int num = 123;
sprintf(buffer, "The number is: %d", num);
printf("%s\n", buffer); // Output: The number is: 123
return 0;
}

In this example, sprintf() formats the string “The number is: %d” with the value of num, which is 123, and stores the resulting string in the buffer. Later, printf() is used to print the contents of buffer to the standard output.