Turn the CString into a char*

Source: Internet
Author: User

Ext.: http://blog.sina.com.cn/s/blog_58e19ae7010003jt.html

Correct method:
CString M_head;
Char *codefile;
codefile= (LPSTR) (LPCTSTR) M_head;Correct, find a way to remove the suffix
Add:
int fnlen = M_head.getlength (); STRCSPN (str, ".");
Codefile=new Char[fnlen+4];
Codefile= (LPSTR) (LPCTSTR) m_head;//correct, find a way to remove the suffix
for (int i=fnlen-1;i>3;i--)//Remove the file suffix. pas
{if (codefile[i]== ' s ') && (codefile[i-1]== ' a ') && (Codefile[i-2]
= = ' P ') && (codefile[i-3]== '. '))
{codefile[i]=codefile[i-1]=codefile[i-2]=codefile[i-3]= ';
break;}
}
Error method 1:int Fnlen = M_head.getlength (); STRCSPN (str, ".");
Codefile=new Char[fnlen+4];
int i=0;//name is incorrect, but is not empty.
for (; i<fnlen;i++)
Codefile[i]=m_head[i];
codefile[fnlen]=0;
Error Method 2:
strcpy (Codefile,m_head.getbuffer (Fnlen)); This sentence will cause the program to abort unexpectedly!
M_head.releasebuffer (Fnlen);
Error Method 3:
strcpy (Codefile,m_head);//This sentence will also let the program abort unexpectedly!
Error Method 4:
Codefile=m_head.getbuffer (Fnlen);//can be executed, but the value of CodeFile is empty

Resources:
CString converted to char?
Cstring::getat this returns a Char

If it is to char *
You can use Cstring:getbuffer to return a char *
In fact, you can also force conversions:
LPCTSTR PCH;
CString Str ("123456");
PCH = (LPCTSTR) str;
The above code is actually the first to let the system perform a forced conversion results, so in fact a bit superfluous ...
But it's safer to do this because char *pbuffer = (LPSTR) (LPCTSTR) str; So the char pointer points to the memory address of the ctring, and if the char is written, because it spans the CString package, It is possible to cause confusion in the CString object, so it is safer to copy a new pointer to char.
If read-only does not write, use char *pbuffer = (LPSTR) (LPCTSTR) str; that's enough!

Turn the CString into a char*

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.