Home > Backend Development > C++ > How to Convert a CString to `const char*` in Unicode MFC Applications?

How to Convert a CString to `const char*` in Unicode MFC Applications?

Linda Hamilton
Release: 2024-10-26 11:38:03
Original
842 people have browsed it

How to Convert a CString to `const char*` in Unicode MFC Applications?

Convert CString to const char* in Unicode MFC Applications

Converting a CString from Unicode (TCHAR) to ASCII (const char*) is essential for interacting with legacy code or external libraries in Unicode MFC applications. Here's how you can achieve this:

Using CT2A Macro

The CT2A macro provides a convenient way to convert a Unicode CString to ASCII. It takes the CString as an argument and an optional second argument to specify the code page. By default, it uses the local code page.

<code class="cpp">// Convert using the local code page
CString str(_T("Hello, world!"));
CT2A ascii(str);
TRACE(_T("ASCII: %S\n"), ascii.m_psz);</code>
Copy after login

Additional Use Cases

The CT2A macro can also be employed to convert a Unicode CString to UTF8 or any other Windows code page:

<code class="cpp">// Convert to UTF8
CString str(_T("Some Unicode goodness"));
CT2A ascii(str, CP_UTF8);
TRACE(_T("UTF8: %S\n"), ascii.m_psz);

// Convert to Thai code page
CString str(_T("Some Thai text"));
CT2A ascii(str, 874);
TRACE(_T("Thai: %S\n"), ascii.m_psz);</code>
Copy after login

CA2T Macro and Compatibility

There is also a complementary CA2T macro that converts from ASCII to Unicode. Both the CT2A and CA2T macros can be used in ATL/WTL applications with Visual Studio 2003 or later.

Additional Resources

For more in-depth information on these macros and code page conversion, refer to the Microsoft Developer Network (MSDN).

The above is the detailed content of How to Convert a CString to `const char*` in Unicode MFC Applications?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template