2022-07-05 16:55:06 +08:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#ifndef csv_reader_h
|
|
|
|
#define csv_reader_h
|
|
|
|
|
|
|
|
#include <fstream>
|
|
|
|
#include <iostream>
|
|
|
|
#include <sstream>
|
|
|
|
#include <string>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
using std::string;
|
|
|
|
using std::vector;
|
|
|
|
|
2022-07-05 19:02:59 +08:00
|
|
|
class CsvReader {
|
2022-07-05 16:55:06 +08:00
|
|
|
public:
|
2022-07-05 19:02:59 +08:00
|
|
|
CsvReader(string);
|
2022-07-06 23:47:50 +08:00
|
|
|
~CsvReader() {};
|
2022-07-05 16:55:06 +08:00
|
|
|
|
|
|
|
public:
|
|
|
|
string file;
|
|
|
|
vector<vector<string>> strArray;
|
|
|
|
|
|
|
|
public:
|
|
|
|
int rows();
|
|
|
|
void readData();
|
2022-07-05 19:02:59 +08:00
|
|
|
string operator()(int i, int j) const;
|
2022-07-05 16:55:06 +08:00
|
|
|
};
|
|
|
|
|
2022-07-05 19:02:59 +08:00
|
|
|
CsvReader::CsvReader(string file_) { file = file_; }
|
2022-07-05 16:55:06 +08:00
|
|
|
|
2022-07-05 19:02:59 +08:00
|
|
|
int CsvReader::rows() { return strArray.size(); }
|
2022-07-05 16:55:06 +08:00
|
|
|
|
2022-07-05 19:02:59 +08:00
|
|
|
void CsvReader::readData() {
|
2022-07-05 16:55:06 +08:00
|
|
|
std::ifstream inFile(file);
|
|
|
|
string lineStr;
|
|
|
|
while (std::getline(inFile, lineStr)) {
|
|
|
|
std::stringstream ss(lineStr);
|
|
|
|
string str;
|
|
|
|
vector<string> lineArray;
|
|
|
|
while (std::getline(ss, str, ',')) lineArray.push_back(str);
|
|
|
|
strArray.push_back(lineArray);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-05 19:02:59 +08:00
|
|
|
string CsvReader::operator()(int i, int j) const {
|
2022-07-05 16:55:06 +08:00
|
|
|
vector<string> lineArray;
|
|
|
|
int n = strArray.size(), m;
|
|
|
|
|
|
|
|
if (i < 0 || i > n - 1) std::cout << "Row Index Out Of Bounds " << std::endl;
|
|
|
|
lineArray = strArray.at(i);
|
|
|
|
m = lineArray.size();
|
|
|
|
if (j < 0 || j > m - 1) std::cout << "Column Index Out Of Bounds " << std::endl;
|
|
|
|
|
|
|
|
return lineArray.at(j);
|
|
|
|
}
|
|
|
|
|
2022-07-05 19:02:59 +08:00
|
|
|
std::ostream& operator<<(std::ostream& cout, CsvReader& cR) {
|
2022-07-05 16:55:06 +08:00
|
|
|
vector<string> lineArray;
|
|
|
|
int n = cR.strArray.size(), m;
|
|
|
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
|
lineArray = cR.strArray.at(i);
|
|
|
|
m = lineArray.size();
|
|
|
|
for (int j = 0; j < m; j++) cout << lineArray.at(j) << " ";
|
|
|
|
if (i < n - 1) cout << std::endl;
|
|
|
|
}
|
|
|
|
|
|
|
|
return cout;
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|