| 139 | } |
| 140 | |
| 141 | void PrintAsCSV(vector<string> const & columns, char const delimiter, ostream & out) |
| 142 | { |
| 143 | bool first = true; |
| 144 | for (string value : columns) |
| 145 | { |
| 146 | // Newlines are hard to process, replace them with spaces. And trim the |
| 147 | // string. |
| 148 | replace(value.begin(), value.end(), '\r', ' '); |
| 149 | replace(value.begin(), value.end(), '\n', ' '); |
| 150 | strings::Trim(value); |
| 151 | |
| 152 | if (first) |
| 153 | first = false; |
| 154 | else |
| 155 | out << delimiter; |
| 156 | bool needsQuotes = value.find('"') != string::npos || value.find(delimiter) != string::npos; |
| 157 | if (!needsQuotes) |
| 158 | { |
| 159 | out << value; |
| 160 | } |
| 161 | else |
| 162 | { |
| 163 | size_t pos = 0; |
| 164 | while ((pos = value.find('"', pos)) != string::npos) |
| 165 | { |
| 166 | value.insert(pos, 1, '"'); |
| 167 | pos += 2; |
| 168 | } |
| 169 | out << '"' << value << '"'; |
| 170 | } |
| 171 | } |
| 172 | out << endl; |
| 173 | } |
| 174 | |
| 175 | class Processor |
| 176 | { |