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;

 

posted @ 2010-06-24 23:13  拂晓风起-Kenko  阅读(2663)  评论(0编辑  收藏  举报