Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <sstream>
- #include <map>
- #include <vector>
- void Tokenize(const string& str,
- vector<string>& tokens,
- const string& delimiters = " ")
- {
- // Skip delimiters at beginning.
- string::size_type lastPos = str.find_first_not_of(delimiters, 0);
- // Find first "non-delimiter".
- string::size_type pos = str.find_first_of(delimiters, lastPos);
- while (string::npos != pos || string::npos != lastPos)
- {
- // Found a token, add it to the vector.
- tokens.push_back(str.substr(lastPos, pos - lastPos));
- // Skip delimiters. Note the "not_of"
- lastPos = str.find_first_not_of(delimiters, pos);
- // Find next "non-delimiter"
- pos = str.find_first_of(delimiters, lastPos);
- }
- }
- class csvReader;
- class csvRow {
- public:
- csvRow(std::vector<std::string> _data, std::map<std::string, int> *_header) {data = _data;header = _header; empty = false;}
- csvRow(bool _empty = false) {empty = _empty;}
- ~csvRow() {}
- // TODO: extend below function to report failure when a col_name not present in headers is used.
- std::string operator[](const std::string &_col_name) const {return data[header->operator[](_col_name)];}
- std::string operator[](int _col_index) const {return data[_col_index];}
- bool isEmpty() {return empty;}
- private:
- bool empty;
- std::map<std::string, int> *header;
- std::vector<std::string> data;
- friend class csvReader;
- };
- class csvReader {
- public:
- csvReader(std::string _filename);
- ~csvReader() {}
- csvRow next();
- private:
- std::ifstream ifs;
- std::map<std::string, int> header;
- };
- csvReader::csvReader(std::string _filename) {
- ifs.open(_filename.c_str());
- std::vector<std::string> header_row = next().data;
- std::vector<std::string>::iterator ii;
- int i;
- for (ii = header_row.begin(), i = 0;
- ii != header_row.end();
- ii++, i++) {
- header[*ii] = i;
- }
- }
- csvRow csvReader::next() {
- std::vector<std::string> result;
- std::string line;
- if(!ifs.eof())
- {
- std::getline(ifs, line);
- std::cout << line << endl;
- Tokenize(line,result,",");
- }
- else
- {
- ifs.close();
- }
- // 1) Make the function exit gracefully when there are no more rows in the csv.
- // (i.e. end of file is reached.)
- // 2) Each row is read into 'line' var. Split it by ',' and insert to result vector, so that the following insert would make sense.
- return csvRow(result, &header);
- }
- int main(void) {
- csvReader rdr("test.csv");
- csvRow current_row = rdr.next();
- while (!current_row.isEmpty()) {
- std::cout << "User: " << current_row["user"] << std::endl
- << "Pass: " << current_row["password"] << std::endl;
- current_row = rdr.next();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement