CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2005
    Location
    Singapore
    Posts
    8

    Visual C++ 2005 char* to CString

    I am writing some MFC application on VC++ 2005 and I have hard time to handling the CString.

    I have some charcter array and I want to convert it to CString but the old method does not work.

    Code:
    CString str;
    char c[] = "Hello";
    str.Format("%s",c);
    AfxMessageBox(str)
    It work on old version but it cannot compile on VC++ 2005. Any suggestion for converting from char* to CString.

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

    Re: Visual C++ 2005 char* to CString

    Quote Originally Posted by zawthet
    Any suggestion for converting from char* to CString.
    Its simple -
    Code:
    char c[] = "Hello";
    CString str (c);
    Or another way -
    Code:
    CString str ("Hello");

  3. #3
    Join Date
    Jun 2002
    Location
    Cambridge, UK
    Posts
    28

    Re: Visual C++ 2005 char* to CString

    There are many flavours that will solve your problem, this is my gut-response.

    Code:
    //CString str;
    //char c[] = "Hello";
    const char *c = "Hello";
    CString str(c);
    //str.Format("%s",c);
    AfxMessageBox(str);
    Basically using the overloaded constructor for CString is the neatest, will work backwards with older compiller, but may also not fit your exact situation, since I doubt you pasted the "real" code in here, and your problem is actually with the definition of the contant c anyway?

    Either way, you want to maybe code more flexibly, either c is constant or it is not, deciding early-on is important, hence I define it as
    Code:
    const char *c = "Hello";
    The C rules have tightened up in 2005 to catch you out when you use loose codeing like the origional definition of c used. Although it's not a total departure from the ANSI spirit to do so, Microsoft have adopted some codeing practices (they can apparently be disabled) that make bugs harder to write.

    WHY
    Sorry you gotta hear this, but the array c is actually an accident looking for a place to happen, because it is possible to do an assignment to c latter on and end up overwritting memory.

    Hopefully further answers to this post will give some official links, but I am not a 2005 user, we are still officially on VC6 in thw eorkplace, so I cannot fiddle right now.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured