使用纯C++STL重写读取CSV表格

来源:互联网 发布:mac下面的图标太多 编辑:程序博客网 时间:2024/06/18 00:24

之前写的读取CSV表格代码是经过封装的C与C++混合代码,最近不断的有机会接触C++的容器与算法库,所以就不断的学习,不断的进步,发现了用STL搜索文本的方法就去改写之前写的代码。

第一步先打开文件

ifstream in("skill.csv");  判断打开是否成功的函数有in.is_open(),in.fail(),in.bad(),in.good()等。

第二步将文件中的内容以行为单位存储在一个map<int, string>变量中。

map<int, string> strmap;
string str;   //临时存储一行的数据(连同逗号一起)
int idx = 0;
while ( getline(in, str) )
{
strmap[++idx] = str;
}

有关getline的信息

  #include <string>  istream& getline( istream& is, string& s, char delimiter = '\n' );
参数信息,is:代表输入流对象,这里指的是文件流对象in。

                  s:用于存储从输入流中读取的内容。

                  delimiter:定界符功能,默认的是行结束符。在读取的过程中getline会自动抛弃定界符,str中不存储。

经过以上代码就把CSV表格中的数据读到了strmap中。strmap中的内容大致上是这样子的

strmap[1]:表格中第一行内容

strmap[2]:表格中第二行内容。。。。等等(这里不包含行结束符)

第三步,针对每一行也就是strmap[i](i = 0,1,2,3...i...总行数n),再把他们按照逗号为定界符进行分割,将分割得到的一系列字符串再存储到一个map<int, string>

void GetParamFromString(string srcstr, map<int, string> &dstmap){string strtemp;std::size_t pospre = 0;std::size_t posnext = 0;int idx = 0;while ( (posnext=srcstr.find_first_of(",", pospre)) !=  string::npos){strtemp = srcstr.substr(pospre, posnext - pospre);pospre = posnext + 1;dstmap[++idx] = strtemp;}strtemp = srcstr.substr(pospre, srcstr.length() - pospre);dstmap[++idx] = strtemp;  //后两行是针对最后一个字段}
上面函数就是根据一行内容srcstr,进行分割,并把没一个字段都存进dstmap中去。

下面代码是循环处理每一行,并把每一行处理后得到的map<int, string>变量存储在map<int, map<int, string>>中。

map<int, map<int, string>> strMap;map<int, string> mapTemp;map<int, string>::iterator it = strmap.begin();int i = 0;for (; it != strmap.end(); ++it){GetParamFromString(it->second, mapTemp);strMap[++i] = mapTemp;}
最后得到的map<int, map<int, string>>对象strMap就是存储了表格中的所有字段。第一个int代表行值(从1开始),第二个int代表列值(从1开始),string存储的是相应行列值中的内容。

原创粉丝点击