What is sprintf in C?
The sprintf function is used to store an output string into a buffer. It allows the output to be formatted before it is stored and does not display it on the console.
Syntax
int sprintf(char *str, const char *format, [arg1, arg2, ... ]);
Parameters
stris a character array on which data is written.formatis a C string that describes the output along with placeholders for the integer arguments to be inserted in the formatted string. It follows the same specifications asprintf().[arg1,arg2...]are the integer(s) to be converted.
Return Value
The return type of the sprintf function is int. If the function is executed successfully, the number of characters written to the buffer, excluding the terminating null character, is returned. For instance, if the size of the buffer is smaller than the size of the formatted output string when the execution fails, sprintf returns a negative value.
Example
In the code below, we allocate a buffer of size 200 bytes and declare two integer variables to store date and time. When the sprintf function is called, it concatenates the strings and data and time integer values that were passed as function arguments together, and stores the new string in the buffer instead of displaying it on the console in the output stream. printf is called later with buffer as its second argument to print the concatenated string. We can see this here:
#include <stdio.h>#include <string.h>int main(){//Declare a buffer of size 200 byteschar buffer[200];int date = 6;int time = 10;//Call sprintf with buffer and the string that needs to be saved into buffer as its parametersint ret = sprintf(buffer, "The date today is %d June 2021 and the time is %d PM%s", date, time, "." );//Call printf to print the contents in bufferprintf("%s", buffer);printf("%s%d%s", "\nThe return value is: ", ret,".");printf("%s%d%s","\nThe size of the formatted string is: ", strlen(buffer),".");return 0;}
Free Resources