swscanf_s
is defined in the wchar.h
header file, reads the provided wide string, formats it according to the format wide string, and finally stores the result into the destinations specified by the additional arguments. What makes swscanf_s
different from the normal swscanf
is that it performs extra run-time checks on the arguments before they are executed.
Following is the declaration syntax for the swscanf_s
function:
The swscanf_s
function takes in 2 mandatory arguments and then a list of additional arguments:
ws
: The pointer to the destination wide string from where to read the data.
format
: The pointer to the format string that may include format specifiers like %ls
.
...
: These are the optional arguments that correspond to the specifiers used in the format string. These arguments are pointers to storage spaces (variables) and must have the same type as their corresponding specifier. This means, e.g. if there’s a %ls
specifier in the format string, there should be a wide character pointer in the additional arguments.
swscanf_s
can return one of the two things:
Upon successful execution, it returns the number of items filled in the list of additional arguments given in the parameters.
If there is a failure during the assignment of arguments or while interpreting an input or if any run-time constraints are violated, EOF
(End Of File) is returned.
The following is an example of how the swscanf_s
function is used to store data read from one string to several other variables:
swscanf_s
reads the given wide string sequentially, and so we must give the list of arguments in the order they are specified in the format wide string.
#define __STDC_WANT_LIB_EXT1__ 1#include <stdio.h>#include <wchar.h>int main (){// the string from which to read datawchar_t to_read [50] = L"Faraz owns 500 acres of land";// variables in which to store datawchar_t name [15];wchar_t unit [15];int amount;// storing#ifdef __STDC_LIB_EXT1__ // only use swscanf_s if __STDC_LIB_EXT1__ is already definedswscanf_s (to_read,L"%ls %*s %d %ls",name,&amount,unit);#endif// use normal swcanf_sswscanf (to_read,L"%ls %*s %d %ls",name,&amount,unit);// print out new wide string using the extracted valueswprintf (L"% d %ls of land is owned by %ls\n",amount, unit, name);return 0;}
All bounds-checked functions (with “_s” suffix in their names) including the
swscanf_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.
In this example, we used the swscanf_s
function to read and store parts of the string corresponding to the amount of land, units of measurement, and the owner’s name, which we then used to print a new string. Note how we did not need the word “owns” in the to_read
wide string. So even though we denoted it by %*s
in the format wide string, it was ignored since we did not give any string pointer argument.
Free Resources