The swprintf
function is defined in the wchar.h
header file. It generates a formatted string using a provided format string and its arguments. This wide string is then stored in the wide string pointed to by the given wide character pointer.
The following is the syntax for the swprintf
function:
The swprintf
function takes in 4 arguments:
wstr
: Pointer to the destination wide string where the formatted wide string will be stored
len
: maximum length of the string that will be stored. Any characters appearing after this length in the formatted wide string will be discarded.
format
: Pointer to the format string which may include format specifiers like %ls
.
args
: The arguments corresponding to the specifiers used (if any) in the format string. This can have from zero to as many arguments as the number of specifiers used in the format
wide string.
swprintf
can have two potential returns values:
A negative number if there is any 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 swprintf
function to generate and copy a formatted wide string to a pointed wide string:
#include <stdio.h>#include <wchar.h>int main (){wchar_t dest_str [50]; // destination wide string arraywchar_t var [10] = L"a ton"; // wide string array to use as argumentint ch_count;// int variable to store the return value of swprintfch_count = swprintf ( dest_str, 50, L"Educative has %ls courses", var );// printing out the destination wide stringwprintf(dest_str);return 0;}
In this example, we declared two wide strings and initialized the one we intend to use as the argument corresponding to the specifier used in the format string. We now use the swprintf
function and pass it a format string along with the argument we created.swprint
then generated the formatted output and stored it in the destination wide string. Finally, we printed out the complete wide string using the wprintf
.
Free Resources