#简介
C++中字符串类的模板原型都是basic_string,string是普通的多字节版本(基于char),而wstring是Unicode版本(基于wchar_t)。
windows 默认unicode为utf16
typedef basic_string<char, char_traits<char>, allocator<char> > string;
typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> > wstring;
#转换
在一些情况下,需要用到string和wstring之间的转换,可以用下面的代码
inline std::string WtoA(const std::wstring &input)
{
std::string dest_str;
int utf8_count =
::WideCharToMultiByte(CP_ACP, 0, input.c_str(), (int)input.length(), NULL, 0, NULL, NULL);
//如果第4个参数为-1,则返回值中包含'\0'
if (utf8_count <= 0)
return dest_str;
dest_str.resize(utf8_count);
if (!::WideCharToMultiByte(CP_ACP, 0, input.c_str(), (int)input.length(), &dest_str[0], utf8_count, NULL, NULL))
{
//转换失败
dest_str.clear();
}
return dest_str;
}
inline std::wstring AtoW(const std::string &input)
{
std::wstring dest_str;
int unicode_count =
::MultiByteToWideChar(CP_ACP, 0, input.c_str(), (int)input.length(), NULL, 0);
//如果第4个参数为-1,则返回值中包含'\0'
if (unicode_count <= 0)
return dest_str;
dest_str.resize(unicode_count);
if (!::MultiByteToWideChar(CP_ACP, 0, input.c_str(), (int)input.length(), &dest_str[0], unicode_count))
{
//转换失败
dest_str.clear();
}
return dest_str;
}
#参考 1.http://msdn.microsoft.com/en-us/library/windows/desktop/dd374081(v=vs.85).aspx