Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đọc và phân tích file CSV trong C++


Nên dùng thư viện để parse CSV trong C++ vì nhiều trường hợp dễ bỏ lỡ nếu tự đọc. Thư viện Boost cung cấp công cụ tốt. Ví dụ:

Ví dụ dùng Boost

#include <iostream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;

vector<string> parseCSVLine(string line) {
    using namespace boost;
    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;
}

Đầu ra

hello
from
here

Cách khác: dùng delimiter phân tách dòng vào mảng.

Ví dụ dùng getline

#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
    stringstream str_strm("hello,from,here");
    string tmp;
    vector<string> words;
    char delim = ',';
    while (getline(str_strm, tmp, delim)) {
        words.push_back(tmp);
    }
    for (auto it = words.begin(); it != words.end(); it++)
        cout << *it << endl;
}

Đầu ra

hello
from
here