How to convert char to wchar in C??

PreludeVT

Member
Oct 14, 1999
96
0
0
ok, I am working on this program, and it requires me to convert a char string[20] to a wide-character type and then past a to a function and then convert the wide-character string back to a regular char string[20] in C?? I am using Visual C++ 6.0 as my IDE. Does anyone know how to do it? thanks.
 

Agaemon

Member
Mar 17, 2001
30
0
0
The only way I could think of to do this is to write two conversion functions. One converts an array of chars to wchar_ts and the other goes back. Below is a sample one that I wrote and compiled in MVC++ 5.0. That should work for you.

#include <string.h>
#include <wchar.h>

void wtoc(wchar_t *toConvert, char *str) {
int count = 0;
int len = wcslen(toConvert);

for(; count < len; count++) {
str[count] = (char) toConvert[count];
}
}

void ctow(char *toConvert, wchar_t *wstr) {
int count = 0;
int len = strlen(toConvert);

for(; count < len; count++) {
wstr[count] = (wchar_t) toConvert[count];
}
}

void convert(wchar_t wstr[20]) {
char copy[20];
wtoc(wstr, copy);
printf(&quot;%s\n&quot;, copy);
}

int main() {
char str[20] = &quot;I hope this works&quot;;
wchar_t wstr[20];
ctow(str, wstr);
convert(wstr);
return 1;
}