C programming stdio.h function - int sprintf(char *str, const char *format, ...)

h‮‬ttps://www.theitroad.com

The sprintf function in the stdio.h library of C programming language is used to write formatted output to a character string, instead of to the console. It has the following syntax:

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

The first argument is a pointer to a character array that will receive the formatted output. The second argument is a format string that specifies the format of the output, and the remaining arguments are the values to be substituted into the format string.

The sprintf function works in the same way as the printf function, but instead of printing the output to the console, it stores the output in the character array pointed to by the first argument.

Here's an example that uses sprintf to format a string and store the output in a character array:

#include <stdio.h>

int main() {
   char str[50];
   int num = 42;
   sprintf(str, "The answer is %d", num);
   printf("%s\n", str);
   return 0;
}

This will store the string "The answer is 42" in the str array and then print it to the console. The size of the str array must be large enough to hold the formatted output, or the function may write beyond the end of the array, causing undefined behavior.