The vswprintf function, found within the C Standard Library, is commonly employed in C and C++ development to format wide-character strings. Despite its utilization of wchar_t for wide characters instead of char for regular characters, it bears similarities to the vsprintf function.
Syntax:
The general syntax for vswprintf is as follows:
#include <wchar.h>
int vswprintf(wchar_t *ws, const wchar_t *format, va_list arg);
- 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:
#include <stdio.h>
#include <wchar.h>
int main() {
wchar_t buffer[100];
int count;
count = vswprintf(buffer, L"Iam, %s Java %d.\n", L"T point", 42);
wprintf(L"Result: %ls\n", buffer);
wprintf(L"Number of wide characters written: %d\n", count);
return 0;
}
- 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 consider a scenario to demonstrate the utilization of the vswprintf function in C++.
#include <stdio.h>
#include <stdarg.h>
#include <wchar.h>
void PrintWide ( const wchar_t * format, ... )
{
wchar_t buffer[256];
va_list args;
va_start ( args, format );
vswprintf ( buffer, 256, format, args );
fputws ( buffer, stdout );
va_end ( args );
}
int main ()
{
wchar_t str[] = L"test string has %d wide characters.\n";
PrintWide ( str, wcslen(str) );
return 0;
}
Output:
Example 2:
Let's consider another instance to demonstrate the functionality of the vswprintf function in the C++ programming language.
#include <bits/stdc++.h>
using namespace std;
void find ( wchar_t* ws, size_t len, const wchar_t *format, ...)
{
va_list arg;
va_start ( arg, format );
vswprintf ( ws, len, format, arg );
va_end ( arg );
}
int main ()
{
wchar_t str[] = L"Java Cpp Tutorial";
wchar_t ws[20];
find(ws, 20, L"JTP is : %ls\n", str);
wprintf(L"%ls", ws);
return 0;
}
Output: