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.
本文探讨了在项目中启用Unicode字符集后所带来的问题及解决方法。介绍了两种不同的转换方式:使用wcstombs()方法进行固定长度的字符串转换,以及通过CT2CA函数实现更灵活的字符串转换。
939

被折叠的 条评论
为什么被折叠?



