C++ Standard Library C++ STL Library

C++ <cwchar> - wcsncpy() Function



The C++ <cwchar> wcsncpy() function is used to copy the first num characters of the wide string pointed to by source, including the null character, to the wide character array whose first element is pointed to by destination.

If the end of the source is found before num characters, destination is padded with additional null wide characters until a total of num characters is reached. If num is reached before the entire string source was copied, the destination is not null-terminated.

The behavior is undefined if the strings overlap.

Syntax

wchar_t* wcsncpy (wchar_t* destination, const wchar_t* source, size_t num);

Parameters

destination Specify pointer to the wide character array where the content is to be copied.
source Specify pointer to the null-terminated wide string to copy from.
num Specify maximum number of characters to copy.
size_t is an unsigned integer type.

Return Value

Returns destination.

Example:

The example below shows the usage of wcsncpy() function.

#include <iostream>
#include <cwchar>
using namespace std;
 
int main (){
  wchar_t str1[100] = L"xyz";
  wchar_t str2[100];
  wchar_t str3[100] = L"Hello World!";

  //replacing the content of str1 and
  //str2 with first 5 characters of str3
  wcsncpy(str1, str3, 5);
  wcsncpy(str2, str3, 5);
  
  //null character manually added to str2
  str2[5] = L'\0';

  wcout<<"str1 is: "<<str1<<"\n";
  wcout<<"str2 is: "<<str2<<"\n";   
  return 0;
}

The output of the above code will be:

str1 is: Hello
str2 is: Hello

❮ C++ <cwchar> Library