Click here to Skip to main content
15,885,435 members
Articles / Desktop Programming / MFC
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.90/5 (19 votes)
2 Apr 2011CPOL 72K   7   7
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...
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 want to specify the code page, UTF-8 encoded for example as the original, here it is:
CString theCStr;
...
std::string STDStr( CW2A( theCStr.GetString(), CP_UTF8 ) );

:)

License

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


Written By
Engineer
France France
I'm an independent Software Developer living in the Alpes Maritimes (aka French Riviera).

Even if in the past I have worked regularily with Fortran, Pascal, Basic (not necessarily Visual), and much more esoteric languages (who knows Prolog, Lotus 123 macros ?), even if I still work from time to time with C#, Java or some "interpreted languages", I'm more specialized in C++.
I work on MFC since the very first version, I enjoy working on Visual Studio 2010, its C++0x features, STL, MFC, boost, WTL ...

Comments and Discussions

 
QuestionMy Vote 5 Pin
Pankaj B Yadav15-Jan-14 0:19
Pankaj B Yadav15-Jan-14 0:19 
Questionconvert string to Cstring? Pin
Vijay Kumbhani29-Oct-13 3:06
Vijay Kumbhani29-Oct-13 3:06 
GeneralMy vote of 5 Pin
Qu Dong24-Sep-13 1:03
Qu Dong24-Sep-13 1:03 
General5! Pin
Pranit Kothari13-Dec-11 1:27
Pranit Kothari13-Dec-11 1:27 
GeneralReason for my vote of 5 Nice,good and not complicated Pin
Pranit Kothari13-Dec-11 1:26
Pranit Kothari13-Dec-11 1:26 
GeneralReason for my vote of 5 simple way to accomplish the task... Pin
Albert Holguin2-Apr-11 18:48
professionalAlbert Holguin2-Apr-11 18:48 
GeneralReason for my vote of 5 Nice. However, be aware that your ap... Pin
Nemanja Trifunovic30-Mar-11 8:12
Nemanja Trifunovic30-Mar-11 8:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.