how to convert CString to string


All replies

  • You need the CHAR pointer from CString, that can be assigned to CString,

    Code Block


    CString xyz = "Name";

    String strX(xyz.operator LPCSTR());




    Wednesday, October 24, 2007 11:52 AM
  • From CString to std:: string, you mean Smile

    CString cs = "...";
    std:: string s = (LPCSTR)xyz;

    Alternatively, call operator LPCSTR directly.
    Wednesday, October 24, 2007 11:55 AM
  • A Simple way is

    Code Block

    CString strVal ="Hello";
     std::string str = strVal;





    Code Block
    CString strVal ="Hello";
     std::string str = strVal.GetBuffer(strVal.GetLength());




    Wednesday, October 24, 2007 2:10 PM
  • This might break the code if you compile the app using the Wide Characters. Isn't LPCSTR implemented only when the app compiled with Single Byte Character support and LPWSTR otherwise? Thats why the LPCTSTR is a macro which switches between them, dependent on the compilation setting.

    The better choice whould be to either use the stringstream and serialize data into it and deserialize the string. This will also skip empty bytes (but can break valid multi-byte characters!!! into single byte chars):

    Code Block

    CString cs;

    // modify cs...

    ::std::stringstream s;

    s << (LPCTSTR)cs;

    std::string str;

    s >> str;

    The other possiblity would by to use std:: strings based on charater types of CString:

    TCHAR is expanded by the compiler to either char or wchar_t.

    //cs is still valid
    typedef :: std::basic_string<TCHAR>    string_type;
    string_type s = (LPCTSTR)cs;

    On the other hand as far as I know CString can contain non zero based strings (which contain '\0' inside) and in this case using the operator to retrieve the content will be fine until the moment where encountered the first '\0' in the string. So in my opinion the correct way of conversion would be:

    Code Block

    //string_type is still defined and cs is a valid CString...

    string_type std_str;

    LPCTSTR strBegin(cs);

    ::std::for_each(strBegin, strBegin+cs.GetLength(), ::std::back_inserter(std_str));

    But this is to much to write each time you need to do a conversion. You can consider introducing a global conversion operator:

    Code Block

    string_type& operator=(string_type& lhs, CString const& rhs)

         LPCTSTR strBegin(rhs);

         ::std::for_each(strBegin, strBegin+rhs.GetLength(), ::std::back_inserter(lhs));

         return lhs;


    //Now you can write:

    CString str1 = _T("alalal");

    string_type std_str;


    But in this case you should think if this operator can have some other side effects in your app...

    Best Regards,

    Friday, October 26, 2007 5:56 PM

    There is a good article on this at codeproject, it tells how to do to and from many different types of strings:


    Friday, October 26, 2007 6:37 PM