Posts Tagged ‘ANSI’

How to convert ANSI string to UNICODE string and vice versa?

July 2, 2008 6 comments

Well quite simple,  but still quite frequently asked in forums… 🙂

There are two macros that does this for us. They are as follows.

Note: You must include atlconv.h


Before using these two macros you have to use this macro too…


Here is a code snippet for you… 😉

#include <atlconv .h>
//An example for converting from ANSI to UNICODE

//use this first

//An ANSI string
LPSTR lpsz_ANSI_String = "An ANSI String";

//ANSI string being converted to a UNICODE string
LPWSTR lpUnicodeStr = A2W( lpsz_ANSI_String )

//Another example for converting from UNICODE to ANSI

//Use this first

//A UNICODE string
LPWSTR lp_UNICODE_STR = L"A Unicode String";

//UNICODE string being converted to a ANSI string

Another option is to call WideCharToMultiByte and MultiByteToWideChar directly, it’s quite easy to use, at least easier than above macros. If you have doubts on usage of above functions then take a look at AfxW2AHelper and AfxA2WHelper functions. Since these are the functions that A2W and W2A internally calls.

Also as a homework take a look at CW2AEX and CA2WEX classes. Will be similar to above macros, looks to me like a  secure version overload.

A TCHAR version of std stream and string classes

Quite simple…

// A TCHAR based std::string
typedef std::basic_string<tchar> tstring;
// A TCHAR based std::ifstream;
typedef std::basic_ifstream</tchar><tchar , std::char_traits<TCHAR> > tstream;
// A TCHAR based std::stringstream
typedef std::basic_stringstream</tchar><tchar , std::char_traits<TCHAR>, std::allocator</tchar><tchar> > tstringstream;

So now no need to worry about UNICODE and ANSI, should work as CString, since TCHAR becomes char/wchar_t based on _UNICODE macro definition.

Also note that stl has provided UNICODE versions of these classes for e.g. wstring, wstringstream, wifstream, but since windows has a type that switches automagically between char/wchar_t, we are making use of it.

So the idea behind this is that stl classes are mostly template based, so this means you can add your own version of an stl class for a custom type just like I’ve done. As a conclusion we can say that std::string can be called a vector<char> but with dedicated string operations.

%d bloggers like this: