我需要在wstring和string之间进行转换。我想到使用codecvt facet应该可以解决问题,但似乎对于utf-8语言环境不起作用。
我的想法是,当我将utf-8编码的文件读入字符时,一个utf-8字符会被读入两个普通字符(这就是utf-8的工作方式)。我想为我在代码中使用的库创建这个utf-8字符串。
有人知道如何做吗?
我已经尝试过这个:
locale mylocale("cs_CZ.utf-8");
mbstate_t mystate;
wstring mywstring = L"čřžýáí";
const codecvt<wchar_t,char,mbstate_t>& myfacet =
use_facet<codecvt<wchar_t,char,mbstate_t> >(mylocale);
codecvt<wchar_t,char,mbstate_t>::result myresult;
size_t length = mywstring.length();
char* pstr= new char [length+1];
const wchar_t* pwc;
char* pc;
// translate characters:
myresult = myfacet.out (mystate,
mywstring.c_str(), mywstring.c_str()+length+1, pwc,
pstr, pstr+length+1, pc);
if ( myresult == codecvt<wchar_t,char,mbstate_t>::ok )
cout << "Translation successful: " << pstr << endl;
else cout << "failed" << endl;
return 0;
该函数在cs_CZ.utf-8语言环境下返回“失败”,而在cs_CZ.iso8859-2语言环境下正常工作。