char *和wchar_t *的相互转换,可使用标准库函数
size_t mbstowcs(wchar_t *wcstr, const char *mbstr, size_t count)和size_t wcstombs(char *mbstr, const wchar_t *wcstr, size_t count)
注意
微软文档对mbstowcs的描述有误,mbstowcs, _mbstowcs_l | Microsoft Docs
若mbstowcs成功地转换了源字符串,它返回已转换的多字节字符的数量。这句话是错误的,应参考cppreference的描述,std::mbstowcs - cppreference.com
成功,则返回写入目标数组的宽字符的数量,不包括L' '。这句才是正解
另外,根据微软文档的描述,若参数wcstr为NULL,函数返回目标字符串的要求大小(以宽字符为单位)
多字节字符串到宽字符串的转换示例
#include <iostream> using namespace std; int main() { setlocale(LC_ALL, ""); const char *mbString = "多字节字符串到宽字符串的转换"; size_t requiredSize = mbstowcs(nullptr, mbString, 0); wchar_t *wcString = new wchar_t[requiredSize + 1]; if (static_cast<size_t>(-1) == mbstowcs(wcString, mbString, requiredSize + 1)) { cout << "Couldn't convert string: invalid multibyte character." << endl; } else { wcout << "wcString: " << wcString << endl; } delete[] wcString; return 0; }
宽字符串到多字节字符串的转换示例
#include <iostream> using namespace std; int main() { setlocale(LC_ALL, ""); const wchar_t *wcString = L"宽字符串到多字节字符串的转换"; size_t requiredSize = wcstombs(nullptr, wcString, 0); char *mbString = new char[requiredSize + 1]; if (static_cast<size_t>(-1) == wcstombs(mbString, wcString, requiredSize + 1)) { cout << "Couldn't convert string: invalid wide character" << endl; } else { cout << mbString << endl; } delete[] mbString; return 0; }