CSVparser.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #ifndef _CSVPARSER_HPP_
  2. # define _CSVPARSER_HPP_
  3. # include <stdexcept>
  4. # include <string>
  5. # include <vector>
  6. # include <list>
  7. # include <sstream>
  8. namespace csv
  9. {
  10. class Error : public std::runtime_error
  11. {
  12. public:
  13. Error(const std::string &msg):
  14. std::runtime_error(std::string("CSVparser : ").append(msg))
  15. {
  16. }
  17. };
  18. class Row
  19. {
  20. public:
  21. Row(const std::vector<std::string> &);
  22. ~Row(void);
  23. public:
  24. unsigned int size(void) const;
  25. void push(const std::string &);
  26. bool set(const std::string &, const std::string &);
  27. private:
  28. const std::vector<std::string> _header;
  29. std::vector<std::string> _values;
  30. public:
  31. template<typename T>
  32. const T getValue(unsigned int pos) const
  33. {
  34. if (pos < _values.size())
  35. {
  36. T res;
  37. std::stringstream ss;
  38. ss << _values[pos];
  39. ss >> res;
  40. return res;
  41. }
  42. throw Error("can't return this value (doesn't exist)");
  43. }
  44. const std::string operator[](unsigned int) const;
  45. const std::string operator[](const std::string &valueName) const;
  46. friend std::ostream& operator<<(std::ostream& os, const Row &row);
  47. friend std::ofstream& operator<<(std::ofstream& os, const Row &row);
  48. };
  49. enum DataType {
  50. eFILE = 0,
  51. ePURE = 1
  52. };
  53. class Parser
  54. {
  55. public:
  56. Parser(const std::string &, const DataType &type = eFILE, char sep = ',');
  57. ~Parser(void);
  58. public:
  59. Row &getRow(unsigned int row) const;
  60. unsigned int rowCount(void) const;
  61. unsigned int columnCount(void) const;
  62. std::vector<std::string> getHeader(void) const;
  63. const std::string getHeaderElement(unsigned int pos) const;
  64. const std::string &getFileName(void) const;
  65. public:
  66. bool deleteRow(unsigned int row);
  67. bool addRow(unsigned int pos, const std::vector<std::string> &);
  68. void sync(void) const;
  69. protected:
  70. void parseHeader(void);
  71. void parseContent(void);
  72. private:
  73. std::string _file;
  74. const DataType _type;
  75. const char _sep;
  76. std::vector<std::string> _originalFile;
  77. std::vector<std::string> _header;
  78. std::vector<Row *> _content;
  79. public:
  80. Row &operator[](unsigned int row) const;
  81. };
  82. }
  83. #endif /*!_CSVPARSER_HPP_*/