如何在C ++中将字符串转换为wstring [英] How to convert string to wstring in C++
问题描述
我已经编程了一些代码,但有一些问题。在这段代码,我试图将字符串转换为wstring。但是这个字符串有█个字符。这个字符有219个ASCII码。
此转换得到错误。
I have programmed some code but there is some problem. In this codes i am trying to convert string to wstring. But this string have "█" characters. This character have 219 ascii code. This conversion getting error.
在我的代码:
string strs =█and█somethingelse
wstring wstr(strs.begin(),strs.end());
调试后,这个
?和?something else
如何解决这个问题?
感谢...
推荐答案
和宽编码使用< cwchar> $>中的
mbsrtowcs
和 wcsrtombs
c $ c>头。我在此答案中说明了这一点。
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.
在C ++ 11,您可以使用合适的 codecvt
构面实例化 wstring_convert
模板。不幸的是,这需要一些自定义绑定,这在 cppreference页面上有详细说明。 。
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.
我在这里修改为一个自包含的示例,将 wstring
转换为 string
,从系统的广义转换为系统的窄编码:
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;
}
这篇关于如何在C ++中将字符串转换为wstring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!