Simple CSV parser that handles quoted fields and escaped quotes example: input: value1,"value, with, commas","value with ""escaped"" quotes",value4 output: [value1] [value, with, commas] [value with "escaped" quotes] [value4]
| 935 | // input: value1,"value, with, commas","value with ""escaped"" quotes",value4 |
| 936 | // output: [value1] [value, with, commas] [value with "escaped" quotes] [value4] |
| 937 | static std::vector<std::string> parse_csv_row(const std::string& input) { |
| 938 | std::vector<std::string> fields; |
| 939 | std::string field; |
| 940 | bool in_quotes = false; |
| 941 | |
| 942 | for (size_t i = 0; i < input.length(); ++i) { |
| 943 | char ch = input[i]; |
| 944 | |
| 945 | if (ch == '"') { |
| 946 | if (!in_quotes) { |
| 947 | // start of quoted field (only valid if at beginning of field) |
| 948 | if (!field.empty()) { |
| 949 | // quote appeared in middle of unquoted field, treat as literal |
| 950 | field += '"'; |
| 951 | } else { |
| 952 | in_quotes = true; // start |
| 953 | } |
| 954 | } else { |
| 955 | if (i + 1 < input.length() && input[i + 1] == '"') { |
| 956 | // escaped quote: "" |
| 957 | field += '"'; |
| 958 | ++i; // skip the next quote |
| 959 | } else { |
| 960 | in_quotes = false; // end |
| 961 | } |
| 962 | } |
| 963 | } else if (ch == ',') { |
| 964 | if (in_quotes) { |
| 965 | field += ','; |
| 966 | } else { |
| 967 | fields.push_back(std::move(field)); |
| 968 | field.clear(); |
| 969 | } |
| 970 | } else { |
| 971 | field += ch; |
| 972 | } |
| 973 | } |
| 974 | |
| 975 | // Add the last field |
| 976 | fields.push_back(std::move(field)); |
| 977 | |
| 978 | return fields; |
| 979 | } |
| 980 | |
| 981 | common_params_context common_params_parser_init(common_params & params, llama_example ex, void(*print_usage)(int, char **)) { |
| 982 | // per-example default params |
no test coverage detected