vswprintf() function in C/C++
The C Standard Library contains the vswprintf() function, which is frequently used in C and C++ programming to format wide-character strings. Though it uses wide characters (wchar_t) rather than regular characters (char), it is comparable to the vsprintf() function.
Syntax:
The general syntax for vswprintf() is as follows:
- ws: A pointer to the resultant string's wide-character array.
- format: A control string for formatting that indicates how arguments after it are transformed for output.
- arg: A variable argument list represented by a va_list
- If successful, the function returns the total number of wide characters written, omitting the null wide character at the end. It returns a negative value if it fails.
- It is similar to vsprintf(), but with the addition of a va_list argument (arg) in place of a variable number of arguments, is the vswprintf() It makes it helpful when you wish to format data into a wide-character string and have a variable argument list.
Here's an easy illustration:
- In this example, a wide-character string is formatted into the buffer array using vswprintf(). After that, the wprintf() prints the resultant string to the console.
- When working with wide-character functions in C or C++, make sure you include the required header files (#include <wchar.h>). Furthermore, exercise caution when utilizing vswprintf() and other similar functions to avoid buffer overflows. Make sure there is always adequate space in the destination buffer to hold the formatted string.
Example 1:
Let's take an example to illustrate the use of the vswprintf() function in C++.
Output:
Example 2:
Let's take another example to illustrate the use of the vswprintf() function in C++.
Output:
|