std::wstring_convert处理UTF8

来源:互联网 发布:php怎么依据浏览者城市 编辑:程序博客网 时间:2024/06/06 08:28

转自:http://www.cppblog.com/mythma/archive/2012/09/11/wstring_convert_utf8.html
扔掉MultiByteToWideChar 吧,使用std::wstring_convert和 std::codecvt_utf8 来处理UTF8与WChar之间的互转。
VC和Clang都支持哦~

#include <iostream>#include <string>#include <locale>#include <codecvt>#include <fstream>int main(int argc, char *argv[]){   std::wstring str = L"123,我是谁?我爱钓鱼岛!";   std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;   std::string narrowStr = conv.to_bytes(str);   {      std::ofstream ofs ("c:\\test.txt");      ofs << narrowStr;   }   std::wstring wideStr = conv.from_bytes(narrowStr);   {      std::locale::global(std::locale("Chinese-simplified"));      std::wofstream ofs (L"c:\\testW.txt");      ofs << wideStr;   }}
原创粉丝点击