lj=_T(".\\")+th+_T("bmp");
_T(char[])等价于cstring
CString a,b, c;
a = "a";
b = "b";
c = a + b; //cstring拼接
方法1 ok:
CString中存储的字符的数据类型为wchar_t类型。
一、CString转换为char *
(1)方法一:使用wcstombs() ok
输出结果:
注意到结果没有输出“计算机网络”,那是因为wcstombs()不支持中文。
(2)方法二:使用WideCharToMultiByte();
输出结果:
二、char *转换为CString
(1)方法一:使用_T()宏
(2)方法二:使用API的函数MultiByteToWideChar()
在str.Append(pWChar);这条语句处设断点,调试运行,可查看到str的内容为"liuxijiao计算机网络"。
(三)方法三:使用A2T()、A2W()
http://blog.csdn.net/candyliuxj/article/details/6796001
1 前言
今天在网上看论坛,发现大家对CString与Char *互转各说一词,其实我发现提问者所说的情况与回答问题的人完全不是同一情况,这里做一总结.
首先大家得清楚一件事,一般在网上提出问题的人大部分使用的都是VC,那么你就应该知道,在VC下编程,工程属性中有一属性Charecter Set属性,其值可以设置为Use Multi-Byte Charecter Set 和 Use Unicode Charecter Set 这两种选择,具默认情况下工程是采用了Use Unicode Charecter Set选项.如我使用的VS2010的工程属性中如下:
VC在处理CString类型字符时,在这两种不种选择的处理结果也是完全不一样的,而网上那么答复大都是针对假设提问者是使用了Use Mult-Byte Chracter Set的前提下,但大多提这个问题的人都是使用了后者的情况的人.
暂且将Use Mult-Byte Chracter Set称之为宽字节字符模式,而Use Unicode Charecter Set称之为Unicode编码模式.
2 宽字节字符模式
首先讨论一下宽字符字符模式下的CStirng与Char *之间的互转,在这种情况下互换很简单:
2.1 CString -->char *
如下:
但好像官方并不建议这么做,而建议采用下面这种方式:
网上也有人说是这样t1 =str1.GetBuffer(0);但其实我在实测时并没发现str1.GetBuffer(str1.GetLenth())与str.GetBuffer(0)返回值有啥区别,MSDN中相应说明如下:
由上可知,GetBuffer的参数nMinBufLength为最小缓冲区长度,但实际结果没啥区别...
2.2 char * -->CString
2.3 CString -->int
在宽字符字符模式下,这个非常简单:
2.4 int -->CString
3 Unicode编码模式
3.1 CString -->char *
在这种情况下,上述所说的转化全是浮云,目前只发现可以用WideCharToMultiByte函数来实现.
如下 :
3.2 char * -->CString
还是可以如下:
3.3 CString -->int
在这种情况下atoi不再适用,其实可以用swscanf,如下:
3.4 int -->CString
这个其实最简单了,如下:
4 结束
另外,有关ANSI与Unicode之间的转换及UTF-8与Unicode之间的转换可以参与下面这个链接:
http://www.cnblogs.com/gakusei/articles/1585211.html
http://blog.csdn.net/flydream0/article/details/8543525
4、cstring转 char*
CString str=_T("你好");
char ch[4];
for(int i=0;i<str.GetLength();i++)
{
ch[i]=str.GetAt(i);
}
https://zhidao.baidu.com/question/1817947422751736028.html
http://bbs.csdn.net/topics/370008804
http://bbs.csdn.net/topics/70379273
引申: cstring转char* 文件名的拼接 数字和字母还有反斜杠的拼接
CString lj;
char a[14]="./";
int i;
//swscanf(th[1],_T("%d"),&i);
//itoa(i,b,10);
wchar_t *pWChar = th.GetBuffer(); //获取th的宽字符用数组保存
th.ReleaseBuffer();
int nLen = th.GetLength(); //获取th的字符数
char *b= new char[nLen * 2 + 1];
memset(b, 0, nLen * 2 + 1);
int rtnVal = (int)wcstombs(b, pWChar, nLen * 2 + 1); //宽字符转换为多字节字符
i = atoi(b);
itoa(i,b,10);
// char b[7]="4";
//char b1[20];
//for(int i=0;i<20;i++)
//{
//
// b1[i]=b[i+1];
//
//}
char c[7]=".bmp";
strcat( a,b);
strcat( a,c);
lj=a;
if(i!=0) //很必要 不然一直是0 由于字符串转为数字时候空格会变为0 所以数字中有很多是0必须过滤掉
{
th=lj;
UpdateData(FALSE); //文件名是th
} //过滤掉0 不然会乱码
if( m_bmp.m_hObject != NULL )//判断
m_bmp.DeleteObject();
/载入图片
//HBITMAP hbmp = (HBITMAP)::LoadImage(AfxGetInstanceHandle(),
//_T(".\\3.bmp"), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION|LR_LOADFROMFILE);
HBITMAP hbmp = (HBITMAP)::LoadImage(AfxGetInstanceHandle(),
th, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION|LR_LOADFROMFILE);
原代码见老园日记