What is swscanf in C?
Defined in the wchar.h header file, swscanf 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.
Syntax
Following is the declaration syntax for the swscanf function:
Parameters
The swscanf 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, which 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%lsspecifier in the format string, there should be a wide character pointer in the additional arguments.
Return value
swscanf 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
EOF(End Of File) is returned.
Example
The following is an example of how the swscanf function is used to store the data read from one string to several other variables.
swscanfreads 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.
#include <wchar.h>int main (){// the wide string to read fromwchar_t to_read [50] = L"Faraz owns 500 acres of land";// variables to serve as destinatons to store different dat from the read stringwchar_t name [15];wchar_t unit [15];int amount;// storing data from the to read string into our variablesswscanf (to_read,L"%ls %*s %d %ls",name,&amount,unit);// printing a new string using data stored in variableswprintf (L"% d %ls of land is owned by %ls\n",amount, unit, name);return 0;}
In this example, we used the swscanf function to read and store parts of the string. These parts correspond 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. Hence, even though we denoted it by %*s in the format wide string since we did not give any string pointer argument, it was ignored.
Free Resources