Sai A Sai A
Updated date Mar 15, 2024
In this blog, we will learn how to convert regular strings to wide strings in C++ using different methods.

Method 1: Using Standard Library Functions

To convert a regular string to a wide string by using the Standard Library functions provided by C++. Specifically, we can use the std::wstring_convert class along with std::codecvt_utf8_utf16 to perform the conversion.

#include <iostream>
#include <locale>
#include <codecvt>

int main() {
    std::string narrowString = "Hello, world!";
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    std::wstring wideString = converter.from_bytes(narrowString);
    std::wcout << wideString << std::endl;
    return 0;
}

Output:

Hello, world!

In this method, we first define a narrow string narrowString. Then, we use std::wstring_convert with std::codecvt_utf8_utf16<wchar_t> to create a converter object capable of converting between UTF-8 and UTF-16 encoded strings. Finally, we use the from_bytes member function of the converter object to convert the narrow string to a wide string and output the result.

Method 2: Using Wide String Literals

Another method to create wide strings directly from regular strings is by using wide string literals. Wide string literals are prefixed with the letter L, indicating that the string should be interpreted as a wide string.

#include <iostream>

int main() {
    const char* narrowString = "Hello, world!";
    const wchar_t* wideString = L"Hello, world!";
    std::wcout << wideString << std::endl;
    return 0;
}

Output:

Hello, world!

In this method, we define a regular string narrowString and a wide string wideString using wide string literals. The L prefix before the string literal indicates that it should be treated as a wide string. We then directly output the wide string using std::wcout.

Method 3: Using Wide Character Iterators

We can also convert regular strings to wide strings using iterators and algorithms provided by the Standard Library.

#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
    std::string narrowString = "Hello, world!";
    std::wstring wideString;
    std::copy(narrowString.begin(), narrowString.end(), std::back_inserter(wideString));
    std::wcout << wideString << std::endl;
    return 0;
}

Output:

Hello, world!

In this method, we first define a narrow string narrowString. Then, we create an empty wide string wideString. We use std::copy it along with std::back_inserter to copy each character from the narrow string to the wide string, effectively converting it. Finally, we output the wide string using std::wcout.

Comments (0)

There are no comments. Be the first to comment!!!