Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CString to const char*

How do I convert from CString to const char* in my Unicode MFC application?

like image 277
Attilah Avatar asked May 13 '09 17:05

Attilah


People also ask

How do I copy a CString to a char array?

This can be done with the help of c_str() and strcpy() function of library cstring. The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.

How do you convert CString to Lpcstr?

Solution 4. CString p; m_editbox->GetWindowText(p); CWND *c = FindWindow(NULL,p); Also the title is no lucky choice, because I think the problem is not the conversion from CString to LPCTSTR . The call to FindWindow() is correct, when it is inside a CWnd derived class.


2 Answers

To convert a TCHAR CString to ASCII, use the CT2A macro - this will also allow you to convert the string to UTF8 (or any other Windows code page):

// Convert using the local code page CString str(_T("Hello, world!")); CT2A ascii(str); TRACE(_T("ASCII: %S\n"), ascii.m_psz);  // 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); 

There is also a macro to convert from ASCII -> Unicode (CA2T) and you can use these in ATL/WTL apps as long as you have VS2003 or greater.

See the MSDN for more info.

like image 141
Rob Avatar answered Oct 06 '22 22:10

Rob


If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.

CString unicodestr = _T("Testing"); CStringA charstr(unicodestr); DoMyStuff((const char *) charstr); 
like image 29
Mark Ransom Avatar answered Oct 06 '22 22:10

Mark Ransom