eis/TestProject/RNG/read_csv.hpp

67 lines
1.7 KiB
C++
Raw Permalink Normal View History

#pragma once
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
namespace ReadCSV {
using std::string;
using std::vector;
const string dir_root = "/users/dsc/code/TestProject/data_files";
template <typename T>
struct ReadCSV {
vector<vector<T>> operator()(string file_name) {
vector<vector<T>> res;
string file_dir = dir_root + "/" + file_name;
std::ifstream infile(file_dir, std::ios::in);
string line;
string word;
using std::is_same_v;
if (!infile.is_open()) {
throw std::runtime_error("Cannot open CSV file: " + file_dir);
}
while (std::getline(infile, line)) {
std::istringstream sin;
sin.str(line);
vector<T> line_data;
while (std::getline(sin, word, ',')) {
if constexpr (is_same_v<T, double>) {
line_data.push_back(std::stod(word));
} else if constexpr (is_same_v<T, int>) {
line_data.push_back(std::stoi(word));
}
}
res.push_back(line_data);
}
return res;
}
};
using ReadCSVF = ReadCSV<double>;
using ReadCSVI = ReadCSV<int>;
template <typename T>
struct FlowData {
ReadCSVF readf;
ReadCSVI readi;
vector<vector<T>> data;
int length;
int cols;
FlowData(string file_name = "D102-1#酸槽数据.csv") {
if constexpr (std::is_same_v<T, double>) {
data = readf(file_name);
} else if constexpr (std::is_same_v<T, int>) {
data = readi(file_name);
}
length = data.size();
cols = data[0].size();
}
double operator()(int index, int col) {
return data[index % length][col % cols];
}
};
using DoubleData = FlowData<double>;
using IntData = FlowData<int>;
}; // namespace ReadCSV