为什么下面的C++代码只打印第一个字符?
我正在尝试将 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 的正确方法吗?从那时起我就知道了另一种方法。但我想知道为什么上面的代码会这样工作?
I am trying to convert a char string to a wchar string.
In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it.
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;
But it prints just c
Is this the right way to convert from char to wchar? I have come to know of another way since. But I'd like to know why the above code works the way it does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
mbtowc
仅转换单个字符。您是否打算使用mbstowcs
?通常您会调用该函数两次;第一个获取所需的缓冲区大小,第二个实际转换它:
如果您更愿意使用
mbstowcs_s
(因为弃用警告),然后执行以下操作:确保通过 setlocale() 或使用
mbstowcs()
版本(例如mbstowcs_l()
或采用区域设置参数的mbstowcs_s_l()
)。mbtowc
converts only a single character. Did you mean to usembstowcs
?Typically you call this function twice; the first to obtain the required buffer size, and the second to actually convert it:
If you rather use
mbstowcs_s
(because of deprecation warnings), then do this:Make sure you take care of locale issues via setlocale() or using the versions of
mbstowcs()
(such asmbstowcs_l()
ormbstowcs_s_l()
) that takes a locale argument.为什么你使用C代码,为什么不以更可移植的方式编写它,例如我在这里要做的是使用STL!
就这么简单,很容易:D
why are you using C code, and why not write it in a more portable way, for example what I would do here is use the STL!
it's so simple it's easy :D
L"Hello World"
字符串前面的前缀 L 使其成为宽字符字符串。
L"Hello World"
the prefix L in front of the string makes it a wide char string.