Boost 範例程式:共享記憶體 - 讀取 CSV 檔案

引入程式碼回上頁

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

#ifndef TCSV_H_#define TCSV_H_#include <iostream>#include <vector>#include <string>#include <boost/algorithm/string.hpp>#include <fstream>using namespace std; namespace Emprogria { typedef std::vector<std::string> FIELDS; typedef std::vector<FIELDS> ROWS; class TCSV { private: FIELDS Split(std::string s); public: TCSV(); virtual ~TCSV(); ROWS Load(std::string csvFile, bool header=true); }; } /* namespace Emprogria */#endif /* TCSV_H_ */

程式碼

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

#include "TCSV.h"namespace Emprogria { TCSV::TCSV() { } TCSV::~TCSV() { } // 解義 CSV 格式資料 FIELDS TCSV::Split(std::string s) { FIELDS result; boost::split(result, s, boost::is_any_of(",")); return result; } // 讀取資料檔 ROWS TCSV::Load(std::string csvFile, bool header) { ifstream csvF; ROWS rows = ROWS(); try { csvF.open(csvFile.c_str()); if (csvF.is_open()) { rows.clear(); std::string buffer; while (!csvF.eof()) { getline(csvF, buffer); // 捨棄欄位檔頭 if (header) { header = false; continue; } // 儲存資料 rows.push_back(this->Split(buffer)); } } csvF.close(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return rows; }; } /* namespace Emprogria */