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>
- 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;
- do
- {
- std::getline(ifs, line);
- cout << line << endl;
- Tokenize(line,result,",");
- }
- while(std::getline(ifs,line));
- 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