相关疑难解决方法(0)

将wstring转换为以UTF-8编码的字符串

我需要在wstring和string之间进行转换.我想,使用codecvt facet应该可以解决问题,但它似乎不适用于utf-8语言环境.

我的想法是,当我将utf-8编码文件读取到字符时,一个utf-8字符被读入两个普通字符(这就是utf-8的工作原理).我想从我的代码中使用的库的wstring表示创建这个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;
Run Code Online (Sandbox Code Playgroud)

它为cs_CZ.utf-8语言环境返回'failed',并且对cs_CZ.iso8859-2语言环境正常工作.

c++ string utf-8 wstring

17
推荐指数
3
解决办法
3万
查看次数

10
推荐指数
2
解决办法
4092
查看次数

标签 统计

c++ ×2

stl ×1

string ×1

unicode ×1

utf-16 ×1

utf-8 ×1

wstring ×1