mbtowc 仅转换单个字符。你的意思是使用mbstowcs?
通常你调用这个函数两次;第一个获得所需的缓冲区大小,第二个实际转换它:
#include <cstdlib> // for mbstowcs
const char* mbs = "c:\\user";
size_t requiredSize = ::mbstowcs(NULL, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
if(::mbstowcs(wcs, mbs, requiredSize + 1) != (size_t)(-1))
{
// Do what's needed with the wcs string
}
delete[] wcs;
如果您更愿意使用mbstowcs_s(因为有弃用警告),那么请执行以下操作:
#include <cstdlib> // also for mbstowcs_s
const char* mbs = "c:\\user";
size_t requiredSize = 0;
::mbstowcs_s(&requiredSize, NULL, 0, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
::mbstowcs_s(&requiredSize, wcs, requiredSize + 1, mbs, requiredSize);
if(requiredSize != 0)
{
// Do what's needed with the wcs string
}
delete[] wcs;
确保通过setlocale() 或使用带有语言环境参数的mbstowcs() 版本(例如mbstowcs_l() 或mbstowcs_s_l())来处理语言环境问题。