1
votes

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!

2
What programming language are you using for this? - Oded
At last, I wrote one conversion function by myself. Thanks Oded. - Dan

2 Answers

3
votes

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';
}
0
votes

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