C语言 在 C 中将 char* 转换为 wchar*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4826189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:38:30  来源:igfitidea点击:

Convert char* to wchar* in C

cunicodecharwchar

提问by Crupuk

I would like to convert a char*string to a wchar*string in C.

我想将char*字符串转换为wchar*C 中的字符串。

I have found many answers, but most of them are for C++. Could you help me?

我找到了很多答案,但大多数都是针对 C++ 的。你可以帮帮我吗?

Thanks.

谢谢。

回答by Nick Dandoulakis

Try swprintfwith the %hsflag.

尝试swprintf%hs标志。

Example:

例子:

wchar_t  ws[100];
swprintf(ws, 100, L"%hs", "ansi string");

回答by user541686

setlocale()followed by mbstowcs().

setlocale()其次是mbstowcs()

回答by Franky Rivera

what you're looking for is

你要找的是

mbstowcs

works just like the copy function from char* to char*

就像从 char* 到 char* 的复制功能一样工作

but in this case you're saving into a wchar_t*

但在这种情况下,您将保存到 wchar_t*

回答by Christoffer

If you happen to have the Windows API availiable, the conversion function MultiByteToWideCharoffers some configurable string conversion from different encodings to UTF-16. That might be more appropriate if you don't care too much about portability and don't want to figure out exactly what the implications of different locale settings are to the string converison.

如果您碰巧有可用的 Windows API,转换函数MultiByteToWideChar提供了一些从不同编码到 UTF-16 的可配置字符串转换。如果您不太关心可移植性并且不想确切地弄清楚不同区域设置对字符串转换的影响,那可能更合适。

回答by mehrdad safa

if you currently have ANSI chars. just insert an 0 ('\0') before each char and cast them to wchar_t*.

如果您当前有 ANSI 字符。只需在每个字符前插入一个 0 ('\0') 并将它们转换为 wchar_t*。