-
April 6th, 2006, 02:56 AM
#1
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.
-
April 6th, 2006, 03:34 AM
#2
Re: Visual C++ 2005 char* to CString
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");
-
April 6th, 2006, 03:43 AM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|