Click here to Skip to main content
11,581,081 members (63,278 online)
Click here to Skip to main content

C++: Converting an MFC CString to a std::string

, 13 Nov 2011 CPOL 4.5K
I am using CString str(_T("Test"));typedef std::basic_string string_t;string_t resStr(str);It works because the CSting has a cast to LPTCSTR.

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

30 Oct 2011
steveb
In UNICODE:CString str = L"Test";std::wstring ws(str);std::string s;s.assign(ws.begin(), ws.end());
1 Nov 2011
Kaqkk79
How about this (assuming your project is set to Unicode)?CString strMyString=L"Test string";std::string strMyStdAnsiStr = CStringA(strMyString);
7 Apr 2011
oleg63
CString m_Name;CT2CA pszName(m_Name);std::string m_NameStd(pszName);Works for me everywhere... :)
2 Apr 2011
jean Davy
As you use CString, you have access to the CW2A ATL macro, assuming that you work with _UNICODE defined, here it is:CString theCStr;...std::string STDStr( CW2A( theCStr.GetString() ) );which will convert to "system encoding on the user's machine" (thanks Nemanja[^] comment !), if you...
29 Mar 2011
CalicoSkies
6 alternatives  
C++: Converting an MFC CString to a std::string
1 Dec 2011
stonexin
LPSTR WideChar2MBCS( const CString& strCS ){ const UINT wLen = strCS.GetLength() + 1; UINT aLen = WideCharToMultiByte(CP_ACP,0,strCS,wLen,NULL,0,NULL,NULL); LPSTR lpa = new char[aLen]; WideCharToMultiByte(CP_ACP,0,strCS,wLen,lpa,aLen,NULL,NULL); return...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

geoyar
Software Developer
United States United States
No Biography provided

| | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 13 Nov 2011
Article Copyright 2011 by geoyar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid