Sign in
Log inSign up

Converting std::string to std::wstring

Jakov Pavlek's photo
Jakov Pavlek
·May 11, 2020

Use-Case Scenario

Sometimes, most usually when working with Unicode in C++, you might need to convert std::string to std::wstring in order to make operations on std::wstring compatible without loss of generality.

The Problem

How to convert std::string to std::wstring?

Solution

Utilities.h

#include <string>
static std::wstring to_wstring(const std::string& stringToConvert);

Utilities.cpp

#include <Utilities.h>
#include <codecvt>
#include <locale>
std::wstring Utilities::to_wstring(const std::string& stringToConvert)
{
    std::wstring wideString = 
        std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(stringToConvert);
    return wideString;
}

Links:

Conversion to std::wstring