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()或使用带有 locale 参数的mbstowcs()
(例如mbstowcs_l()
或)版本来处理语言环境问题。mbstowcs_s_l()