自定义读取CSV文件的ReadCSV类
使用方法为:
ReadCSV rc(“文件名”),用文件名字符串初始化对象
rc.LoadDataFromCSV(vector<vector>& res),rc对象调用LoadDataFromCSV()方法,参数为二维vector数组的引用,数组中存放的类型是字符串。即以二维字符串数组为参数返回csv文件内容。
#ifndef _READCSV_H_
#define _READCSV_H_
#include<string>
#include<fstream>
#include<iostream>
#include<vector>
#include<sstream>
#include<cstdio>
using namespace std;
class ReadCSV {
private:
string dataFile;
public:
ReadCSV(string path) : dataFile(path) {}
ReadCSV() :dataFile(string()) {}
void SetFilePath(string path) {
dataFile = path;
}
void LoadDataFromCSV(vector<vector<string>>& content) {
ifstream ifs;
ifs.open(dataFile.data());
if (ifs.is_open()) {
cout << dataFile << " opening successful." << endl;
}
else {
cout << dataFile << " opening failed" << endl;
return;
}
string line;
while (getline(ifs, line)) {
string columElement;
stringstream stream(line);
content.push_back(vector<string>());
while (getline(stream, columElement, ',')) {
content.back().push_back(columElement);
}
if (!stream && columElement.empty()) {
content.back().push_back("");
}
}
ifs.close();
string checkFile = dataFile + "check.csv";
string outputContent;
ofstream ofs(checkFile.data());
for (auto ite : content) {
for (auto iite : ite) {
outputContent+=iite;
outputContent += ',';
}
outputContent.pop_back();
outputContent.push_back('\n');
}
ofs << outputContent;
ofs.close();
cout << "checking date..." << endl;
ifstream ifssour(dataFile.data());
string strsour;
ifstream ifscheck(checkFile.data());
string strcheck;
while (getline(ifssour, line)) {
strsour += line;
}
ifssour.close();
while (getline(ifscheck, line)) {
strcheck += line;
}
ifscheck.close();
if (strsour == strcheck) {
cout << "load data sucessfully, data passs checking." << endl;
}
else {
cout << "data loaded wrong!!!" << endl;
}
cout << content.size() << " lines of data have been loaded." << endl;
remove(checkFile.data());
}
};
#endif
|