为什么以下C++代码只打印第一个字符?

2 c++ string wchar

我试图将char字符串转换为wchar字符串.

更详细:我试图首先将char []转换为wchar [],然后将"1"附加到该字符串并打印它.

char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;
Run Code Online (Sandbox Code Playgroud)

但它只打印 c

这是从char转换为wchar的正确方法吗?从那时起我就开始了解另一种方式.但我想知道为什么上面的代码按照它的方式工作?

In *_*ico 10

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;
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢使用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;
Run Code Online (Sandbox Code Playgroud)

确保通过setlocale()或使用带有locale参数的mbstowcs()(例如mbstowcs_l()or mbstowcs_s_l())版本来处理区域设置问题.