The sprintf_s
is defined in the stdio.h
header file and is the security-enhanced alternate of the sprintf
function. It uses a format string and corresponding arguments to generate a string that stores in the provided destination string. What makes sprintf_s
different from the normal sprintf
is that it performs extra run-time checks on the arguments before they are executed.
Following is the declaration syntax for the sprintf_s
function:
The sprintf_s
function takes in 4 arguments:
ws
: The pointer to the destination string where the formatted string will be stored
format
: The pointer to the format string, which may include format specifiers like %s
.
...
: The list of arguments corresponding to the specifiers used (if any) in the format string. This can have zero to as many arguments as the number of specifiers used in the format
string.
sprintf_s
can have two potential returns values:
A negative number if there is an error in execution or the length of the formatted string is greater than the given length.
The number of characters in the formatted string in case of successful execution of the function.
Following is an example of how we can use the sprintf_s
function to generate and copy a formatted string to a pointed string:
All bounds-checked functions (with “_s” suffix in their names) including the
sprintf_s
function are only guaranteed to work if__STDC_LIB_EXT1__
is pre-defined by the implementation and if the user defines__STDC_WANT_LIB_EXT1__
toint
1 before includingstdio.h
header file.
//__STDC_WANT_LIB_EXT1__ has to be defined to int 1 for sprintfs to work#define __STDC_WANT_LIB_EXT1__ 1;#include <stdio.h>int main (){// destination string arraychar dest_str [50];// string array to use as argumentchar var [10] = "a ton";// int variable to store the return value of sprintf_sint ch_count;// only use sprintf_s if __STDC_LIB_EXT1__ is already defined#ifdef __STDC_LIB_EXT1__ch_count = sprintf_s ( dest_str, "Educative has %s courses", var );#endif// use sprintf functionch_count = sprintf ( dest_str, "Educative has %s courses", var );// printing out the destination stringprintf(dest_str);return 0;}
In this example, we declared two strings and initialized the one we intend to use as the argument corresponding to the specifier used in the format string. We now check if __STDC_LIB_EXT1__
is defined and then use the sprintf_s
function and pass it a format string along with the argument we created.sprint_s
then generated the formatted output and stored it in the destination string. Finally, we printed out the complete string using the printf
.
Free Resources