C++11标准增加了一些新的类模板用于改进对国际化和本地化的支持。其中,std::wstring_convert、std::codecvt_utf8等类的出现解决了以往C++难以实现在Unicode到UTF-8以及CJK等本地多字节编码之间转换文本的问题,现在终于不用再去劳烦第三方库和MultiByteToWideChar/WideCharToMultiByte等繁琐的WindowsAPI了。

下面的代码演示了如何利用这些新类,结合原有的codecvt机制,将UTF-8编码的原始字符串转换为Unicode,然后再转换为中文GBK编码。

InBlock.gif#include<tchar.h>
InBlock.gif#include<locale>
InBlock.gif#include<codecvt>
InBlock.gif#include<iostream>
InBlock.gif
InBlock.gifint_tmain(intargc,_TCHAR*argv[])
InBlock.gif{
InBlock.gifstd::stringmystring("\xe4\xb8\xad\xe6\x96\x87");//UTF-8编码的“中文”字符串
InBlock.gifstd::wstring_convert<std::codecvt_utf8<wchar_t>>cvt_utf8;//UTF-8<->Unicode转换器
InBlock.gifstd::wstring_convert<std::codecvt<wchar_t,char,std::mbstate_t>>cvt_ansi(newstd::codecvt<wchar_t,char,std::mbstate_t>("CHS"));//GBK<->Unicode转换器
InBlock.gifstd::wstringws=cvt_utf8.from_bytes(mystring);//UTF-8转换为Unicode
InBlock.gifstd::stringmyansistr=cvt_ansi.to_bytes(ws);//Unicode转换为GBK
InBlock.gifstd::cout<<myansistr<<std::endl;
InBlock.gifreturn0;
InBlock.gif}

注:以上代码在VisualStudio2010SP1/2012环境下编译通过。