cstring 转成 char* 的几个方法,老外写的,比较经典

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值