Re: What is the most elegant way to convert string from unicode to ANSI?



"Elegant: is not a term that pops to mind in doing these conversions. There are just
ways, and ways. It all depends on what y ou are trying to accomplish.

For example, if you need to specify a replacement character for unmappable characters and
detect when it happens, you need to do WideCharToMultiByte. As you observe, you need to
call it twice.

If you only need the simplest possible conversion, you can use T2A or W2A. Note that they
themselves call WideCharToMultiByte twice. If you are using VS.NET, you could do an
construction of a CStringA datatype, which will do a WideCharToMultiByte

CStringW w = L"abc";
CStringA a(w);

If you single-step into this (with enough patience) you will discover that, surprise,
surprise, it calls WideCharToMultiByte twice...

If you want to avoid the two calls, you can simply allocate a buffer the same size as the
Unicode buffer, since you know that it is definitely going to be smaller (note that this
only applies to CP_ACP conversions; CP_UTF8, for example, would quite possibly have a
result string longer than the input string!)
joe

On Wed, 17 Aug 2005 17:00:43 +0900, "P" <test@xxxxxxxxxxx> wrote:

>Hi, again.
>I set my project UNICODE, and use TCHAR, wstring, and so on.
>But, some legacy api need ANSI, so I use WideCharToMultiByte(CP_ACP, ...)
>
>If I want to use it properly, I should call this method twice to know exact
>way for char* and
>dynamic allocation and Whew...
>
>Do you have any elegant and beautiful way to convert wstring (or
>CStringT<wchar_t> or wchar_t) to char ?
>Thanks in advance.
>
Joseph M. Newcomer [MVP]
email: newcomer@xxxxxxxxxxxx
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
.