Vswprintf Function In Cc++

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:

Example

#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:

Example

#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 take an example to illustrate the use of the vswprintf function in C++.

Example

#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 take another example to illustrate the use of the vswprintf function in C++.

Example

#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:

Input Required

This code uses input(). Please provide values below: