题
我正在尝试将Char String转换为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;
但是它只是打印 c
这是从Char转到WCHAR的正确方法吗?从那以后我就知道另一种方式。但是我想知道为什么以上代码可以按照它的方式工作?
解决方案
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()
)进行场地论点。
其他提示
您为什么使用C代码,为什么不以更便携的方式编写它,例如我在这里要做的就是使用STL!
std::string src = std::string("C:\\user") +
std::string(" 1");
std::wstring dne = std::wstring(src.begin(), src.end());
wcout << dne;
很简单,很容易:D
l“你好世界”
字符串前面的前缀L使其成为宽字符串。
不隶属于 StackOverflow