none
how to convert CString to const char *

    Question

  • hi,

    i have one function which returns CString object.

    i need to pass that return value to another function which accepts const char *

    i should not change any of the function signature

    when i try to convert from CString to const char * it is giving error message saying it is not possible

    is there any way to convert CSting to const char *

    plz help me

    thanks in advance

    Tuesday, December 05, 2006 4:17 PM

Answers

  • I would suggest trying this simple MFC-based method of conversion from Unicode:

    CString yourString = . . .;

    CStringA ansiString(yourString);

     

    YourFunction(ansiString);

    I hope it works.

     

    Wednesday, December 06, 2006 7:03 AM
  • I'm not an avoid fan of MFC, nor have I used it the last 6 or 7 years, but I seem to recall that you can cast it directly (it should have a user defined conversion operator). The only reason I can come up with for you not being able to cast it is that you are compiling your application for unicode. Check the character set setting in your project properties (ALT-F7) > configuration properties > general. Switch it to multibyte if it's currently anything else.
    Tuesday, December 05, 2006 4:33 PM
    Moderator
  • is there any way to convert CSting to const char *

    Yes. There is a LPCTSTR operator defined for CString. const char* is LPCSTR. If UNICODE is not defined LPCTSTR and LPCSTR are the same. Your code should look like this:

    CString str;

    const char* cstr = (LPCTSTR)str;

    however, I would put it like this:

    CString str;

    const TCHAR* cstr = (LPCTSTR)str;

    Tuesday, December 05, 2006 8:17 PM
  • Also take a look on this FAQ.

     

    Wednesday, December 06, 2006 7:15 AM
  • Try using this approach:

       {
            LPCSTR pszNonUnicode;
           CString strUnicode;
           USES_CONVERSION;
           pszNonUnicode = W2A( strUnicode.LockBuffer( ) );
           strUnicode.UnlockBuffer( );
       }
    Wednesday, December 06, 2006 10:32 AM
  • Suneel,

    If your program is in UNICODE and your function is not, then you might try reading your
    CString into a buffer in BYTE(s) and then casting the buffer to a NON-Unicode char*.

    For Example:


    unsigned short i, length;
    BYTE  ByteBuffer [128]={0};
    TCHAR szCString  [256]={0};


     wsprintf(szCString,TEXT("%s"),szYourCStringString);

     i = 0;
     length = lstrlen(szCString);
     if (length && length < sizeof(ByteBuffer))
     {
       do{
        ByteBufferIdea=(BYTE)(TCHAR)szCStringIdea;
       }while (++i < length);
     }

     //
     //SendCharStringToYourFunction((char*)ByteBuffer));
     //

     memset(szCString,0,sizeof(szCString));
     i = 0;
     length = strlen ((char*)ByteBuffer);
     if (length && length < sizeof(ByteBuffer))
     {
       do{
        szCStringIdea =(TCHAR)ByteBufferIdea;

       }while (++i<length);
     }

    MessageBox(NULL,szCString,TEXT("Tchar String"),MB_OK);

    I am sure a function exits somewhere that does the same thing, so you can probably use the above without too much trouble until you find it...

    JamesSexton


     

    Thursday, December 07, 2006 9:02 PM

All replies

  • I'm not an avoid fan of MFC, nor have I used it the last 6 or 7 years, but I seem to recall that you can cast it directly (it should have a user defined conversion operator). The only reason I can come up with for you not being able to cast it is that you are compiling your application for unicode. Check the character set setting in your project properties (ALT-F7) > configuration properties > general. Switch it to multibyte if it's currently anything else.
    Tuesday, December 05, 2006 4:33 PM
    Moderator
  • is there any way to convert CSting to const char *

    Yes. There is a LPCTSTR operator defined for CString. const char* is LPCSTR. If UNICODE is not defined LPCTSTR and LPCSTR are the same. Your code should look like this:

    CString str;

    const char* cstr = (LPCTSTR)str;

    however, I would put it like this:

    CString str;

    const TCHAR* cstr = (LPCTSTR)str;

    Tuesday, December 05, 2006 8:17 PM
  • I tried the above methods but it is failing as my project character set should support unicode also

    But in that context the text in CString is normal ANSI characters only

    Is ther any way to do it?

    Wednesday, December 06, 2006 6:51 AM
  • I would suggest trying this simple MFC-based method of conversion from Unicode:

    CString yourString = . . .;

    CStringA ansiString(yourString);

     

    YourFunction(ansiString);

    I hope it works.

     

    Wednesday, December 06, 2006 7:03 AM
  • Also take a look on this FAQ.

     

    Wednesday, December 06, 2006 7:15 AM
  • Try using this approach:

       {
            LPCSTR pszNonUnicode;
           CString strUnicode;
           USES_CONVERSION;
           pszNonUnicode = W2A( strUnicode.LockBuffer( ) );
           strUnicode.UnlockBuffer( );
       }
    Wednesday, December 06, 2006 10:32 AM
  • Suneel,

    If your program is in UNICODE and your function is not, then you might try reading your
    CString into a buffer in BYTE(s) and then casting the buffer to a NON-Unicode char*.

    For Example:


    unsigned short i, length;
    BYTE  ByteBuffer [128]={0};
    TCHAR szCString  [256]={0};


     wsprintf(szCString,TEXT("%s"),szYourCStringString);

     i = 0;
     length = lstrlen(szCString);
     if (length && length < sizeof(ByteBuffer))
     {
       do{
        ByteBufferIdea=(BYTE)(TCHAR)szCStringIdea;
       }while (++i < length);
     }

     //
     //SendCharStringToYourFunction((char*)ByteBuffer));
     //

     memset(szCString,0,sizeof(szCString));
     i = 0;
     length = strlen ((char*)ByteBuffer);
     if (length && length < sizeof(ByteBuffer))
     {
       do{
        szCStringIdea =(TCHAR)ByteBufferIdea;

       }while (++i<length);
     }

    MessageBox(NULL,szCString,TEXT("Tchar String"),MB_OK);

    I am sure a function exits somewhere that does the same thing, so you can probably use the above without too much trouble until you find it...

    JamesSexton


     

    Thursday, December 07, 2006 9:02 PM
  • Thanks

    I found the solution

    Friday, December 08, 2006 5:28 AM
  • Hello,

     

    I am also facing the same problem as u had faced.. Can I plz know the solution..

     

    Thanks in advance,

    Regards,

    Smitr.

    Thursday, March 29, 2007 4:10 AM
  • Refer this url,

     

    http://www.codeguru.com/forum/showthread.php?t=231165

     

    You may find something useful

     

    Thanks,

    --Suneel

    Thursday, March 29, 2007 9:28 AM
  • Hallo Suneel,

     Can you please post the solution , how to convert CString to const char*  or atleast some tips., like other experts helped you, could you please help me fix this problem., thanks.

    I m stuck with same problem.

    Many thanks

    Abhi
    Friday, May 02, 2008 9:21 AM
  • Hi Abhi,

     

    Generally problem comes when Unicode characterset was enabled in your project. We can enable/disable Unicode by changing the Character Set property of the project.

     

    If Unicode not enabled, below mentioned procedures will work.

     

    Like....

     

    CString str = "Hello World";

    char *c = (char *)(LPCTSTR)str;

    cout<<c<<endl;

     

    or

     

    CString str = "Hello World";

    char *cstr = str.GetBuffer(str.GetLength());

    cout<<cstr<<endl;

     

    or

     

    http://www.codeguru.com/forum/showthread.php?t=85534

     

    But if we enable Unicode in the project, then the above mentioned methods will not work.

     

    First we need to use _T()

     

    As

     

    CString str = _T("Hello World");

    char *c = (char *)(LPCTSTR)str;

     

    This time..

     

    cout<<c<<endl;

     

    will display only H.

     

    and code

     

    char *cstr = str.GetBuffer(str.GetLength());

     

    will fail to compile.

     

    There are two ways (I know two only) to solve this problem

     

    First method..

     

    You can use wcstombs() method as below...

     

    char cstr[MAX_LENGTH] = "";

    wcstombs(cstr, (TCHAR*)(const TCHAR*)str, MAX_LENGTH);

     

    But the disadvantage is string length is restricted to MAX_LENGTH.

     

    Suppose if we have a string larger than MAX_LENGTH, then this method will fail to copy.

     

    If we have predefined string length, then we can use this method.

     

    The second method can be used even if we do not know the length of source string.

     

    CString str = _T("Hello World");

    string ss = string(CT2CA(str));

    const char *cc = ss.c_str();

     

    Hope ths solves your problem.

     

    Thanks,

    --Suneel.

    • Proposed as answer by lovebridge2u Friday, March 06, 2009 3:05 PM
    Wednesday, May 07, 2008 1:09 PM
  •  

    Quote>char cstr[MAX_LENGTH] = "";

    Quote>But the disadvantage is string length is restricted to MAX_LENGTH.

    Quote>Suppose if we have a string larger than MAX_LENGTH, then this method will fail to copy.

    Quote>If we have predefined string length, then we can use this method.

     

    Since you can get the length of the string using str.GetLength()

    you can dynamically assign the cstr buffer using new or malloc to

    accommodate a string of virtually any size.

     

    - Wayne

    Saturday, May 10, 2008 12:44 AM
  • Hello,
    I have a similar problem.
    I want to convert a Cstring in const char*.
    Look I have :

    CString buf;
    strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf);

    But the function strcpy_s needs a const char*_Src for its last parameter (buf).
    So, I try to do this :

    CString buf;

    char* toto;
    toto = (char*) buf;

    strcpy_s(g_sXPS8ServerAddress, numberOfElements, toto);

    I have this message error : error C2440: 'type cast' : cannot convert from 'CString' to 'char *'.
    Someone can help me, please.
    Monday, May 12, 2008 4:57 PM

  • Quote>I have this message error : error C2440: 'type cast' :
    Quote>cannot convert from 'CString' to 'char *'.


    You should have been able to work out a solution based on the info
    in the other posts in this thread. Have you tried this?

     

    Code Snippet

     

    const char* toto = (LPCTSTR)buf;

     

     

    - Wayne

     

    Monday, May 12, 2008 5:37 PM
  • Yes, I already tried, there is no error message.
    But the problem is in fact, when we debug the program. It can't debug, and it stop on this line.
    I don't know why.
    And, we have this message : Unhandled exception at 0x1022f95b (msvcr80d.dll) in STXM_Control.exe: 0xC0000005: Access violation writing location 0x0064aed8.
    Monday, May 12, 2008 6:17 PM
  •  

    Quote>It can't debug, and it stop on this line.

     

    On which line? On the initialization of the const char *

    or on the strcpy_s?

     

    Post a small, complete example of code which causes the error.


    - Wayne

     

    Monday, May 12, 2008 8:14 PM
  • Tom&Karin:

    Default project is Unicode now. You should be using wcscpy_s or

    _tcscpy_s.

    Monday, May 12, 2008 9:14 PM
  •  Tom&Karim wrote:

    I want to convert a Cstring in const char*.
    Look I have :

    CString buf;
    strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf);

    But the function strcpy_s needs a const char*_Src for its last parameter (buf).

     

    If you need to use ANSI/MBCS (i.e. char * ) strings, you should use CStringA instead of CString. So, your code will work in both ANSI/MBCS and Unicode builds (Unicode build is the default build setting since Visual C++ 2005).

     

    Code Snippet

    CStringA buf; // force ANSI/MBCS

    strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf);

     

     

    Instead, if you want to code in a Unicode-neutral format (i.e. if you want to develop code that builds fine on both ANSI/MBCS and Unicode builds), you should use CString, and you should use TCHAR instead of char, and _tcscpy_s instead of strcpy_s:

     

    I think that in your original code you defined your g_sXPS8ServerAddress as a char * string, maybe something like this:

    Code Snippet

     

     char g_sXPS8ServerAddress[ MAX_STRING_LENGTH ];

     

     

    then you should change this definition to (using TCHAR):

     

    Code Snippet
     TCHAR g_sXPS8ServerAddress[ MAX_STRING_LENGTH ];

     

     

     

    and your C++ code to copy the buffer into g_sXPS8ServerAddress should be:

     

    Code Snippet

    CString buf;

     

     _tcscpy_s(

      g_sXPS8ServerAddress, // destination

      _countof( g_sXPS8ServerAddress ), // number of elements

      buf // source

     );

     

     

    Note the use of _countof to get the correct number of elements (expressed in count of char's in ANSI/MBCS builds, and in count of wchar_t's in Unicode builds).

    BTW: I would suggest to not use those old-style C arrays (like char/TCHAR something[MAX_LENGTH] and related old-style C functions, like strcpy_s), but instead I would use CString (or CStringA or CStringW if you want to make it explicit that you need an ANSI/MBCS or Unicode string).

     

    HTH,

    Giovanni

     

    Tuesday, May 13, 2008 2:36 PM
  • When I debug this programm, it stop on the bold line and send me this message : Unhandled exception at 0x1022f95b (msvcr80d.dll) in STXM_Control.exe: 0xC0000005: Access violation writing location 0x0064aed8.


    _FUNC_PROLOGUE
    errno_t __cdecl _FUNC_NAME(_CHAR *_DEST, size_t _SIZE, const _CHAR *_SRC)
    {
        _CHAR *p;
        size_t available;

        /* validation section */
        _VALIDATE_STRING(_DEST, _SIZE);
        _VALIDATE_POINTER_RESET_STRING(_SRC, _DEST, _SIZE);

        p = _DEST;
        available = _SIZE;
        while ((*p++ = *_SRC++) != 0 && --available > 0)
        {
        }

        if (available == 0)
        {
            _RESET_STRING(_DEST, _SIZE);
            _RETURN_BUFFER_TOO_SMALL(_DEST, _SIZE);
        }
        _FILL_STRING(_DEST, _SIZE, _SIZE - available + 1);
        _RETURN_NO_ERROR;
    }
    Tuesday, May 13, 2008 11:29 PM

  • Hello All,

     Thanks a lot ..My problem is solved..

    Suneeel said it right, it was all about character set settings for me and a little bit change.

    Thank you all

    Cheers,
    Abhi



    Sunday, May 25, 2008 11:47 AM
  • Suneel:

    Some of the answers in this thread are wrong, and others seem overly complicated. The CStringA meythod works, but only because of the (dangerous IMHO) conversion feature build into CString.

    I would just do:

    Code Snippet

    #include <atlbase.h>

    #include <iostream>


    void f(const char* s)
    {
      std::cout << s << std::endl;
    }

    CString str = _T("Testing");
    f(CT2CA(str));



    This says what it means and means what it says -- convert the string. It also works in ANSI build, where CT2CA does nothing.

    Sunday, May 25, 2008 12:41 PM
  • davewilk said:

    Suneel:

    Some of the answers in this thread are wrong, and others seem overly complicated. The CStringA meythod works, but only because of the (dangerous IMHO) conversion feature build into CString.

    I would just do:

    Code Snippet

    #include <atlbase.h>

    #include <iostream>


    void f(const char* s)
    {
      std::cout << s << std::endl;
    }

    CString str = _T("Testing");
    f(CT2CA(str));



    This says what it means and means what it says -- convert the string. It also works in ANSI build, where CT2CA does nothing.

    Thank you davewilk, like you said, some very complicated answers out there when this seems to suffice, certainly for me anyway.

    Friday, June 20, 2008 9:05 AM
  • I would suggest trying this simple MFC-based method of conversion from Unicode:

     

    CString yourString = . . .;

    CStringA ansiString(yourString);

     

    YourFunction(ansiString);

     

    I hope it works.

     

    This way is the best, thanks alot
    Wednesday, December 30, 2009 6:02 PM
  • CString cs = "test";
    const

     

     

    char* p1 = (LPCSTR)cs;

    Monday, January 04, 2010 8:52 AM
  • it works ,thank you so much
    Tuesday, August 06, 2013 8:26 AM