C++ String: How to convert between 'CString' and 'std::string'?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: C++ String: How to convert between 'CString' and 'std::string'?

Hybrid View

  1. #1
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443

    C++ String: How to convert between 'CString' and 'std::string'?

    Q: How to convert between 'CString' and 'std::string'?

    A:

    'CString' to 'std::string':

    Code:
    CString cs("Hello");
    std::string s((LPCTSTR)cs);
    'std::string' to 'CString':

    Code:
    std::string s("Hello");
    CString cs(s.c_str());

    Last edited by Andreas Masur; July 24th, 2005 at 11:14 AM.

  2. #2
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    6,205

    Re: C++ String: How to convert between 'CString' and 'std::string'?

    Quote Originally Posted by Gabriel Fleseriu
    'CString' to 'std::string':

    Code:
    CString cs("Hello");
    std::string s((LPCTSTR)cs);
    std::string cannot always construct from a LPCTSTR i.e. the code will fail for UNICODE builds.

    As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary.

    Like this -
    Code:
      CString cs ("Hello");
    
      // Convert a TCHAR string to a LPCSTR
      CT2CA pszConvertedAnsiString (cs);
    
      // construct a std::string using the LPCSTR input
      std::string strStd (pszConvertedAnsiString);
    Last edited by Siddhartha; July 14th, 2006 at 10:56 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center