读网页数据出乱码解决办法及读汉字乱码解决

一、//就是把网页的utf-8改成GBK

void CCCBGridCtrlTestView::ConvertUtf8ToGBK(CString& strUtf8)
{
   int len=MultiByteToWideChar(CP_UTF8, 0, (LPSTR)(LPCTSTR)strUtf8, -1, NULL,0);
   unsigned short * wszGBK = new unsigned short[len+1];
   memset(wszGBK, 0, len * 2 + 2);
   MultiByteToWideChar(CP_UTF8, 0, (LPSTR)(LPCTSTR)strUtf8, -1, (LPWSTR)wszGBK, len);

   len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, NULL, 0, NULL, NULL); 
  char *szGBK=new char[len + 1];
   memset(szGBK, 0, len + 1);
   WideCharToMultiByte (CP_ACP, 0, (LPCWSTR)wszGBK, -1, szGBK, len, NULL,NULL);

   strUtf8 = szGBK;
   delete[] szGBK;
   delete[] wszGBK;
}

 

//以下为测试:

 

#include   <afxinet.h>
#include <string>

 setlocale(LC_CTYPE,"chs");

CInternetSession session;  
 CInternetFile* file = NULL;   
 try  
 {  
 // 试着连接到指定URL  
 file = (CInternetFile*) session.OpenURL(theUrl);  
 }  
 catch (CInternetException* m_pException)  
 {  
 // 如果有错误的话,置文件为空  
 file = NULL;  
 m_pException->Delete();  
 return FALSE;  
 }  

 // 用dataStore来保存读取的网页文件  
 CStdioFile dataStore;  
 if (file)  
 {  
 CString somecode, allcode; //也可采用LPTSTR类型,将不会删除文本中的\n回车符  
 BOOL bIsOk = dataStore.Open(Filename, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText);  

 if (!bIsOk)  
 return FALSE; 

 string str; 

 // 读写网页文件,直到为空  
 while (file->ReadString(somecode) != NULL) //如果采用LPTSTR类型,读取最大个数nMax置0,使它遇空字符时结束  
 {
  CString &tmp = somecode;
  ConvertUtf8ToGBK(tmp);
  MessageBox(somecode);
 }  

 file->Close();   
 delete file;  

 

二、读汉字乱码

头文件中加入:#include <locale.h>

读文件的函数里加上:setlocale(LC_CTYPE,"chs");

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhang11wu4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值