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

时间:2010-12-20 17:57:39

标签: 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;

但它仅打印c

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

3 个答案:

答案 0 :(得分: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;

如果您更喜欢使用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())处理区域设置问题。

答案 1 :(得分:2)

为什么使用C代码,为什么不以更便携的方式编写代码,例如我在这里要做的就是使用STL!

std::string  src = std::string("C:\\user") +
                   std::string(" 1");
std::wstring dne = std::wstring(src.begin(), src.end());

wcout << dne;

这很简单很简单:D

答案 2 :(得分:0)

L“Hello World”

字符串前面的前缀L使其成为一个宽字符串。