Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- #include <iomanip>
- #include <vector>
- #include <string>
- #include <exception>
- #include <algorithm>
- class CSVParser
- {
- char separator,quote_mark;
- std::string getLine()
- {
- std::string s;
- std::stringstream ss;
- getline(input,s);
- int nrOfQuotes = std::count(s.begin(),s.end(),this->quote_mark);
- ss<<s;
- while(nrOfQuotes%2)
- {
- ss<<"\n";
- getline(input,s);
- nrOfQuotes += std::count(s.begin(),s.end(),this->quote_mark);
- ss<<s;
- }
- if (nrOfQuotes%2)
- throw std::invalid_argument("Wrong qouting order");
- return ss.str();
- }
- public:
- std::stringstream input;
- CSVParser(char _separator=',',char _quote_mark='"') : separator(_separator), quote_mark(_quote_mark) {}
- bool readRecord(std::vector<std::string>& result)
- {
- result.push_back(getLine());
- std::string
- /*
- while (input.peek() != '\n')
- {
- std::string csvElement;
- std::cout << (int)input.peek()<<std::endl;
- if (input.peek() == '"')
- {
- input >> std::quoted(csvElement,'"');
- }else
- {
- std::getline(input, csvElement, ',');
- }
- result.push_back(csvElement);
- }*/
- return !result.empty();
- }
- };
- int main()
- {
- //input
- std::stringstream test1("a,b,\"c\nd\"");
- std::stringstream test11("a,b,\"c");
- std::stringstream test2("a\nb");
- std::stringstream test3("a;'b\nc';'c';''''");
- std::stringstream test4("\"a\",\"b\nc\",\"c\"\n\"d\"");
- std::stringstream test5("\"a\",\"b\nc\",\"c\"\n\"d\"");
- std::stringstream test6("\"a\",\"b\nc\",\"c\"\n\"d\"");
- // result
- std::vector<std::string> result;
- CSVParser parser(';','"');
- parser.input << test4.str();
- //while(parser.readRecord(result))
- parser.readRecord(result);
- {
- std::cout << result.size() << std::endl;
- for(auto& s : result)
- std::cout << s << ",";
- result.clear();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement