C++按行读取文本文件,并通过分隔符取值

现需要在C++中读取文本文件txt,txt文件的编码格式为:UTF-8 无BOM格式编码!C++环境的字符集为:使用多字节字符集!


读取代码如下:

#include 
   
   
    
    
#include
    
    
     
     
#include
     
     
      
      


string UTF8ToGB(const char* str)
{
	string result;
	WCHAR *strSrc;
	LPSTR szRes;

	//获得临时变量的大小
	int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
	strSrc = new WCHAR[i + 1];
	MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);

	//获得临时变量的大小
	i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
	szRes = new CHAR[i + 1];
	WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);

	result = szRes;
	delete[]strSrc;
	delete[]szRes;

	return result;
}

vector
      
      
       
        SplitCString(CString strSource, CString ch)
{
	vector 
       
       
         vecString; int iPos = 0; CString strTmp; strTmp = strSource.Tokenize(ch, iPos); while (strTmp.Trim() != _T("")) { vecString.push_back(strTmp); strTmp = strSource.Tokenize(ch, iPos); } return vecString; } vector 
        
          ReadTxtFile() { char txt[200]; ifstream infile; infile.open("XXX.txt"); if (!infile.is_open()) { //std::cout << "txt文件打开失败" << endl; } vector 
         
           vcs; while (!infile.eof()) { infile.getline(txt, 100); string msg = UTF8ToGB(txt); CString cstr(msg.c_str()); vcs = SplitCString(cstr, ","); vector 
          
            ::iterator ita; //声明一个迭代器 int i = 0; for (ita = vcs.begin(), i = 0; ita != vcs.end(); i++, ita++)//v1.begin()指向v1的第一个元素,v1.end()指向最后元素的下一位置 { cout << "vcs中的" << i << "值:" << vcs[i] << endl ; } //std::cout << msg << endl; } infile.close(); return vcs; } 
           
          
         
       
      
      
     
     
    
    
   
   

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值