1

I have a wchar_t string, for example, L"hao123--我的上网主页", I can convert it to utf8

encoding, the output string is "hao123锛嶏紞鎴戠殑涓婄綉涓婚〉", but finally, I must write this

string to a plain text file, its format is utf16 (I know this from others), "hao123\uFF0D\uFF0D\u6211\u7684\u4E0A\u7F51\u4E3B\u9875".

Because I must save it in C++ std string and then write it to a file, How can I convert

"hao123锛嶏紞鎴戠殑涓婄綉涓婚〉" to "hao123\uFF0D\uFF0D\u6211\u7684\u4E0A\u7F51\u4E3B\u9875" in char or C++ std string ?

Can anyone give me some tips?

Thanks in advance!

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Dan
  • 3,221
  • 7
  • 27
  • 24

2 Answers2

3

In C++11 this can be done with:

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

int main()
{
    std::wstring_convert<std::codecvt_utf16<wchar_t> > myconv;
    std::wstring ws(L"hao123--\x6211\x7684\x4E0A\x7F51\x4E3B\x9875");
    std::string bs = myconv.to_bytes(ws);
    std::cout << bs << '\n';
}
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
0

I wrote on conversion function by myself, for more information, please visit C++ unicode UTF-16 encoding

Community
  • 1
  • 1
Dan
  • 3,221
  • 7
  • 27
  • 24