Advertisement
Guest User

Untitled

a guest
Jun 1st, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <sstream>
  5. #include <map>
  6. #include <vector>
  7.  
  8. class csvReader;
  9.  
  10. class csvRow {
  11. public:
  12. csvRow(std::vector<std::string> _data, std::map<std::string, int> *_header) {data = _data;header = _header; empty = false;}
  13. csvRow(bool _empty = false) {empty = _empty;}
  14. ~csvRow() {}
  15.  
  16. // TODO: extend below function to report failure when a col_name not present in headers is used.
  17. std::string operator[](const std::string &_col_name) const {return data[header->operator[](_col_name)];}
  18. std::string operator[](int _col_index) const {return data[_col_index];}
  19. bool isEmpty() {return empty;}
  20. private:
  21. bool empty;
  22. std::map<std::string, int> *header;
  23. std::vector<std::string> data;
  24. friend class csvReader;
  25. };
  26.  
  27. class csvReader {
  28. public:
  29. csvReader(std::string _filename);
  30. ~csvReader() {}
  31. csvRow next();
  32. private:
  33. std::ifstream ifs;
  34. std::map<std::string, int> header;
  35. };
  36.  
  37. csvReader::csvReader(std::string _filename) {
  38. ifs.open(_filename.c_str());
  39. std::vector<std::string> header_row = next().data;
  40. std::vector<std::string>::iterator ii;
  41. int i;
  42. for (ii = header_row.begin(), i = 0;
  43. ii != header_row.end();
  44. ii++, i++) {
  45. header[*ii] = i;
  46. }
  47. }
  48.  
  49. csvRow csvReader::next() {
  50.  
  51. std::vector<std::string> result;
  52. std::string line;
  53. do
  54. {
  55. std::getline(ifs, line);
  56.  
  57. cout << line << endl;
  58. Tokenize(line,result,",");
  59. }
  60. while(std::getline(ifs,line));
  61. ifs.close();
  62.  
  63.  
  64. // 1) Make the function exit gracefully when there are no more rows in the csv.
  65. // (i.e. end of file is reached.)
  66. // 2) Each row is read into 'line' var. Split it by ',' and insert to result vector, so that the following insert would make sense.
  67.  
  68. return csvRow(result, &header);
  69. }
  70.  
  71.  
  72. int main(void) {
  73. csvReader rdr("test.csv");
  74. csvRow current_row = rdr.next();
  75. while (!current_row.isEmpty()) {
  76. std::cout << "User: " << current_row["user"] << std::endl
  77. << "Pass: " << current_row["password"] << std::endl;
  78. current_row = rdr.next();
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement