项目中需要按行读取文本文件,并对每一行内容进行解析。每一行都是固定的字段数,字段之间用空格隔开。
#include <stdint.h>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
void LinetoVector(const std::string& line, std::vector<std::string>& fields)
{
fields.clear();
std::istringstream ss(line);
std::string tmp;
while(ss >> tmp)
{
fields.push_back(tmp);
}
}
int LoadCanFile(FILE *fp, std::vector<TableLineInfo>& infoVec)
{
infoVec.clear();
if(fp == nullptr)
{
return -1;
}
char line[1024];
std::vector<std::string> fieldsInLineVec;
TableLineInfo itemDesc;
int ret = 0;
bool ignoreFirstLine = false;
while(fgets(line, 1023, fp))
{
char *p = strtrim(line);
int len = strlen(p);
if(len <= 0)
{
continue;
}
fieldsInLineVec.clear();
LinetoVector(std::string(line), fieldsInLineVec);
if (fieldsInLineVec[0].find("#") == 0)
{
continue;
}
if (!ignoreFirstLine)
{
ignoreFirstLine = true;
continue;
}
if(fieldsInLineVec.size() != 6)
{
ret = -2;
break;
}
unsigned char dst = (unsigned char)std::stoi(fieldsInLineVec[1],nullptr,16);
itemDesc.dst = dst;
infoVec.push_back(itemDesc);
}
return ret;
}
//
当字段之间并非空格隔开时,可使用下面这个函数,用指定字符分割字符串:
void split(std::string str, std::string delimit, std::vector<std::string>& result)
{
size_t pos = str.find(delimit);
str += delimit;
while (pos != std::string::npos)
{
result.push_back(str.substr(0, pos));
str = str.substr(pos + 1);
pos = str.find(delimit);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)