Skip to content

Instantly share code, notes, and snippets.

@pmiddend
Created March 24, 2016 18:47
Show Gist options
  • Select an option

  • Save pmiddend/23bd24c135b5b5ceac94 to your computer and use it in GitHub Desktop.

Select an option

Save pmiddend/23bd24c135b5b5ceac94 to your computer and use it in GitHub Desktop.
struct csv_field_result {
std::string const field;
std::string const rest;
};
csv_field_result
parse_csv_field(std::string const &s,char const separator,char const quote) {
if(s.empty())
return csv_field_result{"",""};
if(s[0] != quote) {
std::string::size_type const commapos = s.find(separator);
if(commapos == std::string::npos)
return csv_field_result{s,""};
return csv_field_result{s.substr(0,commapos),s.substr(commapos+1)};
}
std::string field_string;
for(std::string::size_type i{1}; i < s.length(); ++i) {
if(s[i] == quote) {
if(i+1 == s.length())
return csv_field_result{field_string,""};
if(s[i+1] != quote) {
if(s[i+1] == separator)
return csv_field_result{field_string,s.substr(i+2)};
throw std::runtime_error(std::string{"expected ‘"}+separator+"’ after quote, got ‘"+s[i+1]+"’");
}
++i;
}
field_string += s[i];
}
throw std::runtime_error("quote not terminated");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment