您的位置:首页 > 编程语言 > C语言/C++

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

2016-11-26 22:20 330 查看
现需要在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 读取TXT 分隔符