Convert char* to wchar* in C
54,129
Solution 1
Try swprintf
with the %hs
flag.
Example:
wchar_t ws[100];
swprintf(ws, 100, L"%hs", "ansi string");
Solution 2
setlocale()
followed by mbstowcs()
.
Solution 3
what you're looking for is
mbstowcs
works just like the copy function from char* to char*
but in this case you're saving into a wchar_t*
Author by
Crupuk
Updated on April 08, 2020Comments
-
Crupuk about 4 years
I would like to convert a
char*
string to awchar*
string in C.I have found many answers, but most of them are for C++. Could you help me?
Thanks.
-
Benoit over 13 yearsThis is OK as long as the input is an ANSI string.
-
user541686 over 13 years@Benoit: Yeah, there's obviously more to string conversion than calling just a single function. But I didn't give any details since I think this is all the OP's looking for...
-
Crupuk over 13 yearsThe imput come from LdapDirectory, so i guess it's an UTF8 ?
-
Crupuk over 13 yearsi will try this evening , for now i don't have access to a shell.Thanks
-
caf over 13 years@Benoit: There's no such thing as an "ANSI string". This will work if the original string is in the multibyte format corresponding to the currently set locale.
-
Crupuk over 13 yearsI already have found this function, but i can't use it correctly, i just want to encode a string to unicode to send in a mail subject header. Thanks to you
-
caf over 13 years@Crupuk: What format is the source string in? If it's just ASCII, and you want to use it in a UTF-8 mail header, then no transformation is needed.
-
Antonio almost 11 years@NickDandoulakis I think this answer could be very useful, however I found out that swprintf could have 2 possible interfaces, could you please take a look at this question? stackoverflow.com/q/17716763/2436175
-
Nick Dandoulakis almost 11 years@Antonio the interface that requires the buffer length is the portable one.
-
Antonio almost 11 years@NickDandoulakis It won't compile on Mingw 4.5.2 for example, so unfortunately is not general!
-
Octopus almost 11 yearsthis is a good solution when cross compiling to mingw on a linux platform
-
rookie1024 almost 9 yearsNote that this appears to work with any of the printf functions, fortunately.
-
Bemipefe about 4 yearsCan you explain why %hs is the correct flag ? I tried %ls but it doesn't work (at least on windows). According to this article %hs is used for "narrow" string while %ls is used for "wide" string. I'm using wchar_t so I thought that the correct choise was %ls for "wide" string but I was wrong.
-
Nick Dandoulakis about 4 years@Bemipefe, the
%hs
specifies the type of the argument, e.g. "ansi string" which is a narrow string. -
Bemipefe about 4 years@NickDandoulakis Thanks. I feel a little bit stupid. You are right. The whole printed string will be a wide string but you have to specify the original (input) format.
-
Nick Dandoulakis about 4 years@Bemipefe, no problem. No such thing as a stupid question