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

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct