- 1 year ago
Duplicating wide-character string
To duplicate a wide-character string (wstring) in C++, you can use the wcsdup
function from the <cwchar>
header. Here's an example:
cpp#include <iostream>
#include <cwchar>
#include <cstdlib>
int main() {
const wchar_t* original = L"Hello, world!";
// Duplicate the wide-character string
wchar_t* duplicate = wcsdup(original);
if (duplicate == nullptr) {
std::cerr << "Memory allocation failed." << std::endl;
return 1;
}
// Print the original and duplicate strings
std::wcout << "Original: " << original << std::endl;
std::wcout << "Duplicate: " << duplicate << std::endl;
// Free the memory allocated by wcsdup
free(duplicate);
return 0;
}
In the above example:
The original wide-character string is declared using the
L
prefix to indicate a wide string literal.The
wcsdup
function is used to duplicate the original string. It allocates memory for the duplicate string and copies the content of the original string into it.Check if the
wcsdup
function succeeded by verifying if the returned pointer isnullptr
. If the allocation fails, an error message is printed, and the program exits.The original and duplicate strings are then printed using
std::wcout
, which is used for wide-character output.Finally, the memory allocated by
wcsdup
is freed using thefree
function.
Remember to include the <cwchar>
header to use the wcsdup
function and make sure to free the memory allocated by wcsdup
to avoid memory leaks.
This example demonstrates the basic concept of duplicating a wide-character string in C++. You can adapt it to your specific needs by replacing the original string with your desired wide-character string variable.