CSV读取文件

121 阅读1分钟
#pragma once
#include<string>
#include<vector>
#include<fstream>

std::vector<float> split(std::string& line, char delimiter) {

	line += '\n'; //吃掉的回车加上
        std::vector<float> tokens;
	std::string token;
	for (int i = 0; i < line.size(); i++) {
		if (line[i] == '\n' || line[i] == ',') {
			tokens.emplace_back(std::stof(token));
			token.assign("");
		}
		else {
			token += line[i];
		}
	}
	return tokens;
}

std::vector<std::vector<float>> readCSV(const std::string& filename) {
	std::ifstream file(filename);
	std::vector<std::vector<float>> data;
	if (file.is_open()) {
		std::string line;
		while (std::getline(file, line)) {
			data.emplace_back(split(line, ','));
		}
	}
	return data;
}