How to convert string to wstring in C++

心已入冬 提交于 2019-11-28 00:31:31
Kerrek SB

The C-library solution for converting between the system's narrow and wide encoding use the mbsrtowcs and wcsrtombs functions from the <cwchar> header. I've spelt this out in this answer.

In C++11, you can use the wstring_convert template instantiated with a suitable codecvt facet. Unfortunately this requires some custom rigging, which is spelt out on the cppreference page.

I've adapted it here into a self-contained example which converts a wstring to a string, converting from the system's wide into the system's narrow encoding:

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

// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
template <typename Facet>
struct deletable_facet : Facet
{
    using Facet::Facet;
};

int main()
{
    std::wstring_convert<
        deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>> conv;

    std::wstring ws(L"Hello world.");
    std::string ns = conv.to_bytes(ws);

    std::cout << ns << std::endl;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!