Is there more efficient/better way convert wchar_t to wchar?

Hello.

I would like to convert wchar_t* to char*. However if possible I would like to avoid OS specific libraries.

here's code I've made sofar. I am wondering if there is better way to write this function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char * StringToAscII(wchar_t* str){
	int length = wcslen(str);
	char *ascii_string = new char[length + 1];
	char* ascii = (char*)str;
	int lastpos = -1;
	for (int i = 0; i <= length*2; i++)
	{
		if(ascii[i] != '\0'){
			ascii_string[++lastpos] = ascii[i];
		}
	}
	ascii_string[lastpos+1] = '\0';
	return ascii_string;
}
Last edited on
sizeof(wchar_t) is not guaranteed to be 2.
You seem to assume that every second byte in a wchar_t-string is always zero. This is also not the case. Wouldn't make any sense, would it?
You will have to interpret each wchar individually depending on the used encoding.
If you don't want to ask your OS follow LJBorges.
Otherwise maybe Boost.Locale can be of help, or ICU... There are quite a few unicode-libs out there.
Thanks.
Topic archived. No new replies allowed.