CString 在_UNICODE宏定义下和普通ASCII编码下的不同

CString在普通ASCII编码情况下,系统默认是跟char*差不多的方式来存储(个人觉得)。

例如,声明和赋值一个CString可以这样:

char* charStr = "Kenko";

CString cstr =  charStr;

因为在ASCII编码下,CString会把后边这个指针的内存位置,作为输入流,逐个字符的读入到CString中。

 

但在_UNICODE宏定义下,默认都变为宽字节。那么CString存储方式将以宽字节的形式。

所以此时要CString变为wchar_t*只要如下:

CString变wchar*:
wchar_t unicodeStr[255];
wcscpy(unicodeStr, cstr);

这时要赋值给CString,就注意一定要以宽字节的形式赋值(当然直接用char*赋值给CString,系统会自动转化)。

但例如截取网页之类的,输入的字节流还是ASCII,所以会出现问题。

我在编程过程中,就以ASCII编码字节流赋值,导致在后续查找字符串的时候总是找不到。后边找到问题根源后,就把从CString得到的wchar_t*强制转化为char*。具体问题根源在代码注释中有写。

代码如下,是关于用CInternetSession,截取网页内容的。

 
  
1 // 建立连接,发送请求,接收数据
2   CInternetSession httpsession;
3 CString Line;
4 CString result;
5
6 CInternetFile * webfile = NULL;
7
8 if (url == NULL) return false ;
9 try
10 {
11 wchar_t unicodeStr[ 255 ];
12 wcscpy(unicodeStr, CComBSTR(url));
13 webfile = (CInternetFile * )httpsession.OpenURL(unicodeStr);
14 if (webfile)
15 {
16 int i = 0 ;
17 while (webfile -> ReadString(Line) && i < 300 )
18 {
19 result = result + Line;
20 i ++ ;
21 }
22 }
23 delete webfile;
24 httpsession.Close();
25 wchar_t unicodeStr2[ 3000 ];
26 wcscpy(unicodeStr2, result);
27 /* 因为CString在读取网页时输入的是ASCII编码字节流,
28 但系统默认是接受宽字节的,所以把网页的GB2312 ASCII编码字节流每两字节读取
29 例如网页本来有1000个字符,按上边代码得到的CString GetLength只有500
30 所以这里转化为wchar_t*后,做一个强制转化就行了 */
31 char * charresult = ( char * )unicodeStr2;
32 string strresult(charresult); // char* 转 string
33
34 // 从html文件中得到具体信息
35   int begin = strresult.find( " <body> " ) + 6 ;
36 int end = strresult.find( " </body> " );
37 strresult = strresult.substr(begin, end - begin);
38 strcpy(resultString,strresult.c_str());
39
40 return true ;

 

转载于:https://www.cnblogs.com/kenkofox/archive/2010/06/24/1764793.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值