如何在 C++ 中读取 TSV(制表符分隔值)

此最小示例展示如何在 C++ 中读取和解析制表符分隔值(TSV)文件。我们使用 boost::algorithm::split 将每行拆分为制表符分隔的组件。

read_tsv.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost::algorithm;

int main(int argc, char** argv) {
    ifstream fin("test.tsv");
    string line;
    while (getline(fin, line)) {
        // 将行拆分为制表符分隔的部分
        vector<string> parts;
        split(parts, line, boost::is_any_of("\t"));
        // TODO 你的代码放在这里!
        cout << "First of " << parts.size() << " elements: " << parts[0] << endl;
    }
    fin.close();
}

Check out similar posts by category: C/C++