Aminos
Aminos

Reputation: 871

Is MFC CString a wide char string

I'm working on a win32 project with CStrings (console application), and I noticed something odd when I want to pass to a function (like strtok_s for example) a LPSTR pointer from a CString with the method GetBuffer(), this last one instead of giving me a LPSTR, it gave me a LPWSTR (a pointer to a wide string)... CString is supposed to store 8 bit chars isn't it ?

I'm obliged in some cases to use CStringA for example to be able for example to use the method Find() because with a CString my input string must be a wide one. But in other another project (windowed program), I don't have this problem, i'm suspecting the headers (when I use afxstr.h "Find" works with a normal string, but not with afxcoll.h...)

Usually I work with std::string that's why I'm lost.

Upvotes: 2

Views: 2503

Answers (1)

IInspectable
IInspectable

Reputation: 51395

CString is a typdef, declared as (afxstr.h):

typedef ATL::CStringT< TCHAR, StrTraitMFC< TCHAR > > CString;
// Or, when using the MFC DLL
typedef ATL::CStringT< TCHAR, StrTraitMFC_DLL< TCHAR > > CString;

Depending on what TCHAR is, a CString stores either an ANSI (MBCS) or Unicode string. There are also explicit instantiations of the CStringT template: CStringW and CStringA.

Either type has a conversion constructor, taking a constant pointer to the respective other character encoding. In other words: You can construct a CStringW from an ANSI (MBCS) string, as well as a CStringA from a UTF-16LE-encoded Unicode string.

If you need to be explicit about the character encoding, use either CStringW or CStringA.


Full documentation for CString is available at CStringT Class.

Upvotes: 10

Related Questions