Last active
November 7, 2020 06:51
-
-
Save SolemnJoker/60238ab6535068e89429f24c46e3c4b3 to your computer and use it in GitHub Desktop.
[read csv by cpp] c++读取csv文件 #c++ #csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "csv.h" | |
inline | |
std::vector<std::string> split_csv_line(const std::string& str) { | |
char seperator = ','; | |
std::vector<std::string> results; | |
std::string::size_type start = str.find_first_not_of(' '); | |
std::string::size_type sep = str.find(seperator); | |
while (sep != std::string::npos) { | |
if (start < sep) | |
results.emplace_back(trim(str.substr(start, sep - start))); | |
start = sep + 1; | |
sep = str.find(seperator, start); | |
} | |
if (start != str.size()) | |
results.emplace_back(trim(str.substr(start))); | |
return results; | |
} | |
std::vector<std::string> CsvReader::read_first_line(){ | |
if(!ifs_.is_open()){ | |
return {}; | |
} | |
auto pos = ifs_.tellg(); | |
DEFER{ ifs_.seekg(pos,std::ios::beg); }; | |
std::string line_str; | |
std::getline(ifs_, line_str); | |
if(line_str.empty()){ | |
return {}; | |
} | |
return split_csv_line(line_str); | |
} | |
std::vector<std::string> CsvReader::read_line(){ | |
if(!ifs_.is_open()){ | |
return {}; | |
} | |
std::string line_str; | |
std::getline(ifs_, line_str); | |
if(line_str.empty()){ | |
return {}; | |
} | |
return split_csv_line(line_str); | |
} | |
std::vector<std::vector<std::string> > CsvReader::read_all(){ | |
std::vector<std::vector<std::string> > res; | |
std::vector<std::string> line; | |
do{ | |
line = read_line(); | |
if(!line.empty()){ | |
res.emplace_back(line); | |
} | |
}while(!line.empty()); | |
return res; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <tuple> | |
#include <vector> | |
#include <string> | |
#include <fstream> | |
class CsvReader{ | |
public: | |
CsvReader(std::string csv_file){ifs_.open(csv_file);}; | |
~CsvReader(){ ifs_.close();}; | |
bool is_open(){return ifs_.is_open();}; | |
std::vector<std::string> read_line(); | |
std::vector<std::string> read_first_line(); | |
std::vector<std::vector<std::string>> read_all(); | |
private: | |
std::ifstream ifs_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment