ควรใช้ library แทนการ parse เอง เพราะ CSV มีกรณีขอบมาก (quotes, escaped commas, newlines ใน field)
วิธีที่ 1: ใช้ Boost.Tokenizer (แนะนำ)
#include <iostream>
#include <boost/tokenizer.hpp>
#include <vector>
#include <string>
using namespace std;
using namespace boost;
vector<string> parseCSVLine(string line) {
vector<string> vec;
tokenizer<escaped_list_separator<char>> tk(line, escaped_list_separator<char>('\\', ',', '\"'));
for (auto i = tk.begin(); i != tk.end(); ++i)
vec.push_back(*i);
return vec;
}
int main() {
string line = "hello,from,here";
auto words = parseCSVLine(line);
for (auto it = words.begin(); it != words.end(); it++)
cout << *it << endl;
}
ผลลัพธ์
hello from here
วิธีที่ 2: ใช้ getline กับ delimiter แบบง่าย (ไม่รองรับ quotes/escapes)
stringstream str_strm("hello,from,here");
string tmp;
vector<string> words;
char delim = ',';
while (getline(str_strm, tmp, delim))
words.push_back(tmp);
วิธีที่ 2 ใช้ได้เฉพาะ CSV เรียบง่าย ไม่มี comma/quotes ใน field