Click here to Skip to main content
15,886,199 members
Articles / Desktop Programming / MFC

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 Nov 2011CPOL 10.6K  
How about this (assuming your project is set to Unicode)?CString strMyString=L"Test string";std::string strMyStdAnsiStr = CStringA(strMyString);

Alternatives

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

Please Sign up or sign in to vote.
30 Oct 2011steveb
In UNICODE:CString str = L"Test";std::wstring ws(str);std::string s;s.assign(ws.begin(), ws.end());
Please Sign up or sign in to vote.
7 Apr 2011oleg63
CString m_Name;CT2CA pszName(m_Name);std::string m_NameStd(pszName);Works for me everywhere... :)
Please Sign up or sign in to vote.
2 Apr 2011jean 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...
Please Sign up or sign in to vote.
13 Nov 2011geoyar
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.
Please Sign up or sign in to vote.
29 Mar 2011CalicoSkies 6 alternatives  
C++: Converting an MFC CString to a std::string
Please Sign up or sign in to vote.
1 Dec 2011stonexin
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)


Written By
Software Developer (Senior)
Hungary Hungary
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions