Skip to content

Instantly share code, notes, and snippets.

@korczis
Created September 1, 2014 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korczis/ed532a320e98bde63eeb to your computer and use it in GitHub Desktop.
Save korczis/ed532a320e98bde63eeb to your computer and use it in GitHub Desktop.
How to parse CVS using C++ boost::spirit
// See http://stackoverflow.com/questions/18365463/how-to-parse-csv-using-boostspirit
#include <boost/tokenizer.hpp>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
int main() {
const std::string s = R"(1997,Ford,E350,"ac, abs, moon",""rusty"",3000.00)";
// Tokenizer
typedef boost::tokenizer< boost::escaped_list_separator<char> , std::string::const_iterator, std::string> Tokenizer;
boost::escaped_list_separator<char> seps('\\', ',', '\"');
Tokenizer tok(s, seps);
for (auto i : tok)
std::cout << i << "\n";
std::cout << "\n";
// Boost Spirit Qi
qi::rule<std::string::const_iterator, std::string()> quoted_string = '"' >> *(qi::char_ - '"') >> '"';
qi::rule<std::string::const_iterator, std::string()> valid_characters = qi::char_ - '"' - ',';
qi::rule<std::string::const_iterator, std::string()> item = *(quoted_string | valid_characters );
qi::rule<std::string::const_iterator, std::vector<std::string>()> csv_parser = item % ',';
std::string::const_iterator s_begin = s.begin();
std::string::const_iterator s_end = s.end();
std::vector<std::string> result;
bool r = boost::spirit::qi::parse(s_begin, s_end, csv_parser, result);
assert(r == true);
assert(s_begin == s_end);
for (auto i : result)
std::cout << i << std::endl;
std::cout << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment